Jakob S.
Jakob S.

Reputation: 1891

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

Upvotes: 4

Views: 1801

Answers (2)

Hans Passant
Hans Passant

Reputation: 942478

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.

Upvotes: 7

Reed Copsey
Reed Copsey

Reputation: 564911

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.

Upvotes: 2

Related Questions