Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push data from unmanaged to managed code?

I am using a C++/CLI Wrapper to access a purely C++ library (-> unmanaged) from a C# framework (-> managed). I want to build in a mechanism which enables the C++ library to push information about its status towards the framework. In my understanding this means that I will have to call at least a managed function from unmanaged code at some point. Is this possible and how can I achieve this?

Many thanks for your help!

Best regards, Jakob

like image 637
Jakob S. Avatar asked Jan 20 '23 07:01

Jakob S.


2 Answers

Use a delegate to let unmanaged code call a managed method. Marshal::GetFunctionPointerForDelegate() creates a stub that takes care of the transition, calling an instance method is supported. You can cast the returned pointer to a function pointer usable by the unmanaged code.

You'll find a full code sample in this answer.

like image 157
Hans Passant Avatar answered Jan 31 '23 17:01

Hans Passant


I would recommend using a (managed) event for this. You could have your C++ wrapper call a method on your C++/CLI generated class which raises the event.

The event can easily be subscribed to from the C# side, and used like any other C# based event.

like image 36
Reed Copsey Avatar answered Jan 31 '23 18:01

Reed Copsey