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

安稳与你 提交于 2019-11-29 10:10:11

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!