开发者

Possible to call a managed DLL from unmanaged C++?

Is it possible to call CLR DLL (one for example which is ma开发者_运维问答de with C#) from unmanaged 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜