views:

34

answers:

1

We have a C++/CLI class, let us call it class A, from which we would like to register a non-static callback ("MyNonStaticCallback") into an unmanaged C++ class (class B).

e.g.

void MyNonStaticCallback(void* ...)
{
    // Raise a C# event from this code
}

// Register callback into class B
myClassBInstance->RegisterCallback(..., &MyNonStaticCallback, ...); 

The reason why we want a non-static callback is because we want to raise a C# event from this callback function.

I understand it ain't possible to pass an instance's data member as a function pointer. What would be the best way to proceed here ?

Thanks and Best Regards,

Romain

+1  A: 

Use Marshal.GetFunctionPointerForDelegate Method to get function pointer passed to unmanaged code. Replace void* with IntPtr in MyNonStaticCallback, which matches unmanaged void*. Create delegate instance by general C++/CLI rules.

Alex Farber
It * almost * works, but I'm having now a "Run-Time Check Failure #0" which leads me to think there might be a problem with one of my function's declaration.
optimum
Show your code.
Alex Farber
Fixed. The issue was with the IntPtr which is * not * exactly the same as a void *.
optimum
Right, `IntPtr` HAS A `void *`, there's no IS A relationship. You have to call `ToPointer` on the `IntPtr` to get the `void *` out.
Ben Voigt