Well simple code is a bit hard in this case but here is a try...
If I have to (I'll talk about using the COM interop layer below), I usually wrap .Net objects in mixed mode C++ assemblies. In this kind of operation you compile some of your C++ files with the /clr switch, while others are compiled as straight unmanaged C++. In this case, I will wrap your function in a wrapper class, because this allows you to wrap .Net instances as well as functions.
So you would create a MC++ files that looks like -
MyExporter.h:
using namespace ExposedFunctionNamespace;
public __gc class MyExporter
{
int MyExposedFunction(int X1, int X2)
{
return ExposedFunctionNamespace::ExposedFunction(X1, X2);
}
};
MyExporter.cpp:
#include "MyExporter.h"
#include <vcclr.h>
gcroot<MyExporter*> MyExporterObject = new MyExporter();
In C++ your would write -
// This is the actual entry to managed space the gcroot template ensures
// unmanaged code that is not GC aware can safely interact with CLR
// objects.
#include <vcclr.h>
extern gcroot<MyExporter*> MyExporterObject;
__declspec(dllexport) int MyExposedFunction(int X1, int X2)
{
return MyExporterObject->ExposedFunction(X1, X2);
}
OK the above is not really enough, but you should be able to get a feel for the basic steps. In general the approach I take to interop with unmanaged code is to minimize the exposure of my .Net classes to basic types only. but for non-trival examples this starts to get more and more difficult and time consuming.
COM Interop via TLBExp
Now if you can afford it (perf wise), and you have a strong stomach you can always do the following:
tlbexp <your-C#-assembly>
This will produce a TLB file that can be directy used in standard C++ COM code. So in this case you would implement a completely normal C++ DLL that would use .Net code via the standard COM interop marshalling framework. This approach allows you some freedom in the design of your C# objects. You'll most likely want design you C# objects for easy interop with COM callers and then make a pure C++ layer that handles the DLL exposure for you (basically providing access to your .NET/COM objects via C functions).
Like I said above, if you can afford the overhead of marshalling, then using the later approach allows you to concentrate on your object design without worrying about the managed C++ details. Managed C++ will give you much finer grained control but it comes at a cost in terms of complexity. If you choose the COM route, you should think about limiting your .Net classes public interfaces to reference only each other and basic types (strings, ints, floats, etc). This prevents you from pulling in mscorlib.tlb into you COM interfaces. It doesn't hurt to pull in mscorlib, but my preference is to keep things minimal when doing this kind of exposure work.
Hope this helps,
Kevin
This posting is provided "AS IS" with no warranties, and confers no rights.