Click here to Skip to main content
14,211,624 members
Click here to Skip to main content
Tip/Trick
Posted 11 Dec 2013

Stats

152K views
8.2K downloads
39 bookmarked

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

,
Rate this:
4.82 (28 votes)
Please Sign up or sign in to vote.
4.82 (28 votes)
13 Dec 2013     CPOL    
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.

// 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.

// 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.

// 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)

Share

About the Author

CathalMF
United States United States
No Biography provided

Comments and Discussions

 
Questionyou are mistaking a very basic of C/C++ Pin
Member 116277472-Aug-18 20:04
memberMember 116277472-Aug-18 20:04 
Questionthanks Pin
Member 1252329021-May-18 5:34
memberMember 1252329021-May-18 5:34 
QuestionThe missing steps not in the original posting Pin
Wendel Renner28-Aug-17 4:52
memberWendel Renner28-Aug-17 4:52 
QuestionNeed consultant to accomplish calling C# function from C++ Pin
Wendel Renner25-Aug-17 4:27
memberWendel Renner25-Aug-17 4:27 
QuestionBuilds ok but... can't build in my application Pin
stevecodeproject24-Aug-16 4:40
memberstevecodeproject24-Aug-16 4:40 
Hi,

I'm using VS2010. The downloaded code builds and executes fine under the Release profile but not under Debug. My code fails to find the System namespace when compiled with a test application. I used VS2010 to create a new solution, created a Console C++ app called "TestApp" with the same _tmain() as the project code and copied ManagedCSharp\ and ManagedDll\ into the new solution and added them, confirming dependencies were correct. I added the library and had to add the ManagedDLL.h path to the project. Both these DLL projects build ok in my new solution. My TestApp fails to build though. E.g.

1> ManagedCSharp -> E:\Projects\TestApp\ManagedCSharp\bin\Release\ManagedCSharp.dll
2> Copying file from "E:\Projects\TestApp\ManagedCSharp\bin\Release\ManagedCSharp.dll" to "E:\Projects\TestApp\Release\ManagedCSharp.dll".
...
2> Creating library E:\Projects\TestApp\Release\ManagedDll.lib and object E:\Projects\TestApp\Release\ManagedDll.exp
...
3>------ Rebuild All started: Project: TestApp, Configuration: Release Win32 ------
3>Build started 8/24/2016 3:21:38 PM.
3>_PrepareForClean:
3> Deleting file "Release\TestApp.lastbuildstate".
3>InitializeBuildStatus:
3> Touching "Release\TestApp.unsuccessfulbuild".
3>ClCompile:
3> stdafx.cpp
3> TestApp.cpp
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(5): error C2871: 'System' : a namespace with this name does not exist
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(6): error C2653: 'System' : is not a class or namespace name
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(6): error C2871: 'Reflection' : a namespace with this name does not exist
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(11): error C2059: syntax error : 'public'
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(12): error C2143: syntax error : missing ';' before '{'
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(12): error C2447: '{' : missing function header (old-style formal list?)
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(23): error C2039: 'DoWork' : is not a member of 'ManagedDll'
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(23): error C2065: 'DoWork' : undeclared identifier
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(23): error C2146: syntax error : missing ';' before identifier 'work'
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(23): error C2065: 'work' : undeclared identifier
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(24): error C2065: 'work' : undeclared identifier
3>E:\Projects\TestApp\ManagedDll\ManagedDll.h(24): error C2228: left of '.ShowCSharpMessageBox' must have class/struct/union
3> type is ''unknown-type''
3>
3>Build FAILED.


I've compared project settings in both my & the downloaded solutions and can't see any differences. Both the DLLs (C++ & C#) compile ok & use the /clr directive.

My App is a multibyte application rather than Unicode so I changed the downloaded TestApp property to match mine & the downloaded one still compiles ok so it's nothing to do with Unicode/multibyte code as far as I know.

What have I missed?

Thanks, Steve
AnswerRe: Builds ok but... can't build in my application Pin
rabbit only26-May-17 1:27
memberrabbit only26-May-17 1:27 
QuestionHow to pass a String and int Pin
wang200230-Jan-16 14:58
memberwang200230-Jan-16 14:58 
AnswerRe: How to pass a String and int Pin
MiCRo_5-Dec-17 7:46
memberMiCRo_5-Dec-17 7:46 
AnswerRe: How to pass a String and int Pin
Member 1252329021-May-18 5:33
memberMember 1252329021-May-18 5:33 
GeneralMy vote of 5 Pin
Aqua_Aria23-Nov-15 18:20
memberAqua_Aria23-Nov-15 18:20 
QuestionError Pin
Member 1177530818-Jun-15 5:26
memberMember 1177530818-Jun-15 5:26 
AnswerRe: Error Pin
Greg Mulvihill20-Sep-15 4:19
memberGreg Mulvihill20-Sep-15 4:19 
AnswerRe: Error Pin
Michael Waters3-Jan-19 11:34
memberMichael Waters3-Jan-19 11:34 
Question__declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Pin
Sai Gopinath Dokku18-May-15 17:41
memberSai Gopinath Dokku18-May-15 17:41 
AnswerRe: __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention Pin
MiCRo_5-Dec-17 6:35
memberMiCRo_5-Dec-17 6:35 
SuggestionNice! Pin
Shawn-USA6-May-15 18:07
memberShawn-USA6-May-15 18:07 
Question64 bit? Pin
KodeMnke26-Apr-15 6:12
memberKodeMnke26-Apr-15 6:12 
Questionuseful Solution Pin
Member 1163486823-Apr-15 23:23
memberMember 1163486823-Apr-15 23:23 
GeneralMy vote of 1 Pin
Sergey Alexandrovich Kryukov19-Mar-15 14:03
memberSergey Alexandrovich Kryukov19-Mar-15 14:03 
GeneralRe: My vote of 1 Pin
BigTimber@home23-Dec-15 3:50
professionalBigTimber@home23-Dec-15 3:50 
GeneralRe: My vote of 1 Pin
Sergey Alexandrovich Kryukov23-Dec-15 5:30
memberSergey Alexandrovich Kryukov23-Dec-15 5:30 
GeneralRe: My vote of 1 Pin
Member 1209768521-Dec-16 6:00
memberMember 1209768521-Dec-16 6:00 
GeneralRe: My vote of 1 Pin
Sergey Alexandrovich Kryukov21-Dec-16 17:23
memberSergey Alexandrovich Kryukov21-Dec-16 17:23 
GeneralRe: My vote of 1 Pin
David Thielen24-Mar-17 11:48
memberDavid Thielen24-Mar-17 11:48 
QuestionFramework-specific compiling error Pin
Member 1141304814-Feb-15 12:55
memberMember 1141304814-Feb-15 12:55 

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.

Layout: fixed | fluid

Article Copyright 2013 by CathalMF
Everything else Copyright © CodeProject, 1999-2019

Server Web01
Version 2.8.190619.2