Click here to Skip to main content
15,885,216 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 277.5K   11.9K   46   54
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

 
QuestionQuestion how would the c# sharp library call a method in the cppclr project? callback method from c# to the clr project Pin
Member 1616904823-Dec-23 6:11
Member 1616904823-Dec-23 6:11 
Question.NET Core (.NET 6)? Pin
AxeManGa197630-Jan-22 16:12
AxeManGa197630-Jan-22 16:12 
QuestionHow would you do this with other types, such as a string? Pin
Member 1492533328-Aug-20 10:37
Member 1492533328-Aug-20 10:37 
AnswerRe: How would you do this with other types, such as a string? Pin
Justin 202423-Feb-24 5:34
Justin 202423-Feb-24 5:34 
Question64-bit Pin
Member 148618152-Jul-20 20:26
Member 148618152-Jul-20 20:26 
AnswerRe: 64-bit Pin
Aced2X29-Jul-20 5:00
Aced2X29-Jul-20 5:00 
GeneralRe: 64-bit Pin
Justin 202423-Feb-24 5:55
Justin 202423-Feb-24 5:55 
AnswerRe: 64-bit Pin
Pavel Eremeev9-Nov-22 21:53
Pavel Eremeev9-Nov-22 21:53 
Question1>TestApp.obj : error LNK2019: unresolved external symbol "void __cdecl ShowMessageBox(int *)" (?ShowMessageBox@@YAXPAH@Z) referenced in function _wmain Pin
Member 1435748513-Jan-20 22:51
Member 1435748513-Jan-20 22:51 
AnswerRe: 1>TestApp.obj : error LNK2019: unresolved external symbol "void __cdecl ShowMessageBox(int *)" (?ShowMessageBox@@YAXPAH@Z) referenced in function _wmain Pin
Member 148618152-Jul-20 20:32
Member 148618152-Jul-20 20:32 
GeneralRe: 1>TestApp.obj : error LNK2019: unresolved external symbol "void __cdecl ShowMessageBox(int *)" (?ShowMessageBox@@YAXPAH@Z) referenced in function _wmain Pin
Coco_Yen5-Jan-21 13:54
Coco_Yen5-Jan-21 13:54 
QuestionWorks perfectly with C++-Application but not with C-DLL Pin
Member 1105861225-Jul-19 19:54
Member 1105861225-Jul-19 19:54 
Questionyou are mistaking a very basic of C/C++ Pin
Member 116277472-Aug-18 20:04
Member 116277472-Aug-18 20:04 
AnswerRe: you are mistaking a very basic of C/C++ Pin
Naveen .R.S26-Apr-23 20:17
Naveen .R.S26-Apr-23 20:17 
Questionthanks Pin
Member 1252329021-May-18 5:34
Member 1252329021-May-18 5:34 
QuestionThe missing steps not in the original posting Pin
Wendel Renner28-Aug-17 4:52
Wendel Renner28-Aug-17 4:52 
QuestionNeed consultant to accomplish calling C# function from C++ Pin
Wendel Renner25-Aug-17 4:27
Wendel Renner25-Aug-17 4:27 
QuestionBuilds ok but... can't build in my application Pin
stevecodeproject24-Aug-16 4:40
stevecodeproject24-Aug-16 4:40 
AnswerRe: Builds ok but... can't build in my application Pin
rabbit only26-May-17 1:27
rabbit only26-May-17 1:27 
QuestionHow to pass a String and int Pin
wang200230-Jan-16 14:58
wang200230-Jan-16 14:58 
AnswerRe: How to pass a String and int Pin
MiCRo_5-Dec-17 7:46
MiCRo_5-Dec-17 7:46 
AnswerRe: How to pass a String and int Pin
Member 1252329021-May-18 5:33
Member 1252329021-May-18 5:33 
GeneralRe: How to pass a String and int Pin
Member 1461293213-Sep-20 11:39
Member 1461293213-Sep-20 11:39 
GeneralMy vote of 5 Pin
Aqua_Aria23-Nov-15 18:20
Aqua_Aria23-Nov-15 18:20 
QuestionError Pin
Member 1177530818-Jun-15 5:26
Member 1177530818-Jun-15 5:26 

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.