tags:

views:

94

answers:

3

Is it possible to call CLR DLL (one for example which is made with C#) from Undamaged C++ code?

I need a DLL that is not managed to call into it somehow, maybe even via some proxy C++ process that is built with C++ / CLI?

+5  A: 

The CLR DLL would have to be built as a COM visible assembly. If you have control of the C#, it's a simple rebuild, otherwise, is pretty much impossible to use it directly.

SWeko
@Hamish, care to elaborate?
David Gladfelter
Added "...to use it directly." Otherwise the meaning was wrong, sorry.
SWeko
+3  A: 

@SWeko gave you the best answer if you can modify the original DLL and your unmanaged code can rely on having access to a COM apartment (either its own thread with ::CoInitialize() called or the calling thread of the unmanaged code has a consistent apartment).

If that's not the case, then the best solution is to create a "managed" C++ DLL as a wrapper on the managed C# assembly. It's called C++/CLI. You can expose unmanaged C API operations and inside the implementation of those, delegate to the managed API's. It works pretty well and unlike calling COM API's, there are no thread affinity issues.

David Gladfelter
+2  A: 

I'm not sure it fits, but perhaps "Reverse PInvoke" is an option.

If you can first call from your C# to your C++ then you can provide a .net delegate to the C++ where it is able to be used as a function pointer. You can then call from your C++ to C# using that function pointer.

public delegate int Read(int target);
[DllImport("yourC++.dll")]
static extern void RegisterRead(Read x);
Read m_Read = new Read(yourClass.Read);

RegisterRead(m_Read);

There can be some tricks with the GC collecting the delegate early, whatever class has the delegate may need to be pinned if it is not just used immediatly in RegisterRead

Greg Domjan