Yes, the C ++ / CLI compiler makes this easy. It automatically generates a "thunk", which guarantees the loading of the CLR when an unmanaged program calls an exported function. It is best to demonstrate an example.
Starting with C # code, create a new project from the class library project template. You will need to write the static method needed because the C code knows nothing about classes. Here is a simple example:
using System; namespace ClassLibrary1 { public static class Mumble { public static int method(int arg) { return arg; } } }
Right-click the solution name in the Solution Explorer window, Add + New Project. Select Visual C ++, CLR, Class Library. Right-click the new project, "Properties", "General Properties", "Structure and Links", click "Add New Link". Projects, select a C # project.
Open the .cpp file and write the code as follows:
#include "stdafx.h" using namespace ClassLibrary1; extern "C" __declspec(dllexport) int method(int arg) { return Mumble::method(arg); }
Build. This DLL can now be used by your unmanaged code, it can call the function "method". Both this DLL and your C # DLL need to be copied to the unmanaged program directory.
Remember that calling this method incurs overhead. Thunk, which the C ++ / CLI compiler generates, provides enough work to ensure that the CLR is loaded and initialized. Debugging will be invalid (use Debugger.Break ()), and uncaught managed exceptions will crash your program with very poor diagnostics.
source share