Click here to Skip to main content
15,844,009 members
Articles / Programming Languages / C#
Tip/Trick

Calling C# .NET methods from unmanaged C/C++ code

Rate me:
Please Sign up or sign in to vote.
4.83/5 (32 votes)
13 Dec 2013CPOL1 min read 272.4K   11.8K   46   52
Describes with an example of how you can call C#.NET methods from unmanaged C++ code.

Introduction

For a number of reasons which I won't get into, I needed to use a C# .NET DLL from unmanaged code. I spent a long time looking for the answer before figuring it out. So I thought I'd post the example here to spread the word.

The way it works is fairly straightforward and requires three components:

  1. C# DLL doing whatever.
  2. Managed C++ DLL with exposed C function. This DLL will call your C# DLL methods. 
  3. Unmanaged C++ application/DLL which will call the exposed C function in the Managed C++ DLL.

Using the code

Create your C# DLL. The below example just shows a simple MessageBox and sets the result of the value based on OK or CANCEL.

C#
// ManagedClass.cs

// Any source code blocks look like this
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ManagedCSharp
{
    public static class ManagedClass
    {
        public static void ShowValue(ref int value)
        {
            DialogResult result = MessageBox.Show("C# Message Box", 
                    "C# Message Box", MessageBoxButtons.OKCancel);

            if (result == DialogResult.OK)
                value = 1;
            else
                value = 2;
            return;
        }
    }
}

Create a Managed C++ DLL and reference it in your C# project.

This exports your function ShowMessageBox in an unmanaged format.

Inside the exported function, call the Managed C++ method which calls your C# methods.

MC++
// ManagedDll.h

#pragma once

using namespace System;
using namespace System::Reflection;

namespace ManagedDll {    

    public ref class DoWork
    {
        public:void ShowCSharpMessageBox(int *value)
        {            
            ManagedCSharp::ManagedClass::ShowValue(*value);
            return;
        }
    };
}

__declspec(dllexport) void ShowMessageBox(int *value)
{
    ManagedDll::DoWork work;    
    work.ShowCSharpMessageBox(value);    
}

Create your unmanaged C or C++ DLL or EXE and call the exposed C++ method in your managed code.

In your unmanaged project setting, you will need to reference the ManagedDll.lib file created by the ManagedDll project and build time.

MC++
// TestApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "conio.h"
#include <iostream>
#include <windows.h>

_declspec(dllexport) void ShowMessageBox(int *value);


int _tmain()
{
    int *result;

    ShowMessageBox(result);

    if(*result == 1)
        printf("Ok Was Pressed \n");
    else
        if(*result == 2)
            printf("Cancel Was Pressed \n");
        else
            printf("Unknown result \n");

    system("pause");

    return 0;
}

Find the attached full project which should build straight away. Built in Visual Studio 2008.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError Pin
Member 1177530818-Jun-15 6:26
Member 1177530818-Jun-15 6:26 
AnswerRe: Error Pin
Greg Mulvihill20-Sep-15 5:19
Greg Mulvihill20-Sep-15 5:19 
GeneralRe: Error Pin
Member 1231187320-Oct-22 1:08
Member 1231187320-Oct-22 1:08 
AnswerRe: Error Pin
Michael Waters3-Jan-19 12:34
Michael Waters3-Jan-19 12:34 
Question__declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Pin
Sai Gopinath Dokku18-May-15 18:41
Sai Gopinath Dokku18-May-15 18:41 
AnswerRe: __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Pin
MiCRo_5-Dec-17 7:35
MiCRo_5-Dec-17 7:35 
AnswerRe: __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Pin
Pavel Eremeev9-Nov-22 23:07
Pavel Eremeev9-Nov-22 23:07 
SuggestionNice! Pin
Shawn-USA6-May-15 19:07
Shawn-USA6-May-15 19:07 
As others pointed out, this is to call C# .NET methods from unmanaged C/C++ indirectly via C++/CLI.

If anyone wants to call C# .NET methods from native C/C++ code directly. The best solution is to use Reverse P/Invoke along with other interop technologies. You will be able to call C# .NET method from native C/C++ directly without using C++/CLI.

Question64 bit? Pin
KodeMnke26-Apr-15 7:12
KodeMnke26-Apr-15 7:12 
Questionuseful Solution Pin
Member 1163486824-Apr-15 0:23
Member 1163486824-Apr-15 0:23 
GeneralMy vote of 1 Pin
Sergey Alexandrovich Kryukov19-Mar-15 15:03
mvaSergey Alexandrovich Kryukov19-Mar-15 15:03 
GeneralRe: My vote of 1 Pin
BigTimber@home23-Dec-15 4:50
professionalBigTimber@home23-Dec-15 4:50 
GeneralRe: My vote of 1 Pin
Sergey Alexandrovich Kryukov23-Dec-15 6:30
mvaSergey Alexandrovich Kryukov23-Dec-15 6:30 
GeneralRe: My vote of 1 Pin
Member 1209768521-Dec-16 7:00
Member 1209768521-Dec-16 7:00 
GeneralRe: My vote of 1 Pin
Sergey Alexandrovich Kryukov21-Dec-16 18:23
mvaSergey Alexandrovich Kryukov21-Dec-16 18:23 
GeneralRe: My vote of 1 Pin
_kb_26-Dec-20 1:13
_kb_26-Dec-20 1:13 
AnswerLinks in my past answer Pin
Sergey Alexandrovich Kryukov26-Dec-20 5:07
mvaSergey Alexandrovich Kryukov26-Dec-20 5:07 
GeneralRe: My vote of 1 Pin
David Thielen24-Mar-17 12:48
David Thielen24-Mar-17 12:48 
QuestionFramework-specific compiling error Pin
Member 1141304814-Feb-15 13:55
Member 1141304814-Feb-15 13:55 
QuestionTesting Problem Pin
Member 1141304813-Feb-15 9:45
Member 1141304813-Feb-15 9:45 
AnswerRe: Testing Problem Pin
Member 1209768521-Dec-16 5:13
Member 1209768521-Dec-16 5:13 
QuestionHow to response the event of managed class Pin
Adam Xiang10-Jul-14 21:35
Adam Xiang10-Jul-14 21:35 
AnswerRe: How to response the event of managed class Pin
Shawn-USA6-May-15 19:11
Shawn-USA6-May-15 19:11 
QuestionIs this possible in windows phone 8? Pin
Member 1062996111-Jun-14 1:18
Member 1062996111-Jun-14 1:18 
QuestionCan't get this to work, please help Pin
erezlevi5-May-14 10:46
erezlevi5-May-14 10:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.