简体   繁体   中英

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

Is it possible to call CLR DLL (one for example which is made 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM