Link to home
Start Free TrialLog in
Avatar of jxbma
jxbmaFlag for United States of America

asked on

How do I call C# managed callback methods from unmanaged C++ code?

Hi:

I've got the following class definition defined in unmanaged C++:
class Listener
{
public:
	virtual void onStarted() = 0;
	virtual void onStopped() = 0;
        virtual void onResults(std::vector<Foo> foo, Results results) = 0;
};

Open in new window

This class is consumed by an unmanaged C++ library (of which I can' t really change the implementation).

How do I wrap this class in C++/CLI so it can be:
1) Consumed by C# (managed client)
2) The C# implementation will provide definitions for the virtual functions.
     The unmanaged library needs to call the onStarted() & onStopped() callbacks
     I can't change the underlying unmanaged C++ implementation (as we have existing unmanaged C++ clients)
     How do I do this?

Thanks,
JohnB
Avatar of sarabande
sarabande
Flag of Luxembourg image

you have to make a mixed-code c++ wrapper dll which transfers the unmanaged class into a managed class. in a mixed-code dll you can mix unmanaged code with managed code and access unmanaged classes/functions from managed code this way.  the c# then would use the managed class provided by the dll.

you may search for "IJW" (it just works) to get samples of mixed code projects.

Sara
Avatar of jxbma

ASKER

sarabande>> Thanks for the quick response.

I created a C++ wrapper class for this.
The part I'm confused about is the callbacks themselves would work.
I've got some standard CLI/C++ wrappers defined, and they make sense.

It's not clear to me how to specifically write the wrapper for this abstract (interface).
Can you provide example based on my code snippet or point me to a similar
definition?

Thanks,
JohnB
ASKER CERTIFIED SOLUTION
Avatar of sarabande
sarabande
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial