Andy
Andy

Reputation: 3799

Callbacks from C++ to C#

I have a subject/observer system in C++:

#include <vector>
class IObserver
{
public:
    virtual void valueChanged(float pos) = 0; 
};

class Subject
{
public:
    static Subject *instance();
    void subscribe(IObserver *observer);
private:
    static Subject*                    m_instance;
    std::vector<IObserver*>            m_observers;
};

I need to implement an observer in C# and subscribe to the subject. How do I do this?

I could maybe use function pointers:

typedef void (*ValueChangedFunc)(float pos);
void SubscribeTovalueChanged(ValueChangedFunc func); // global but works on singleton

How would I convert a C# member function to a C++ function pointer and call the last function?

Upvotes: 0

Views: 2198

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283634

C# can't implement C++ interfaces, that needs to be done from C++.

You can either use C++/CLI to make a shim observer implementing the interface that also understands C# delegates, or you can use standard C++ to make a shim observer implementing the interface and calling a function pointer; C# delegates can be converted to function pointers.

A final way is for the C++ code to use a full-blown COM interface (described in IDL), which C# can implement, instead of a minimal C++ interface.


For your new code with function pointers:

First, specify the calling convention on the C++ side.

typedef void (__stdcall *ValueChangedFunc)(float pos);
void __stdcall SubscribeToValueChanged(ValueChangedFunc func); // global but works on singleton

Then declare a delegate matching the function-pointer typedef.

[UnmanagedFunctionPointer(CallingConvention.Stdcall)]
delegate void ValueChangedFunc(float);

And then declare the function that consumes it:

[DllImport(...)]
void SubscribeToValueChanged(ValueChangedFunc func);

Note that function pointers in use in native code are not visible to the garbage collector. It is your responsibility to keep the delegate alive for as long as the function pointer is stored.

Upvotes: 5

Related Questions