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:
- C# DLL doing whatever.
- Managed C++ DLL with exposed C function. This DLL will call your C# DLL methods.
- 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
.
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.
#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.
#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.