I've written C# code that passes a delegate to be called by C++ as a function pointer. When the C++ code calls the function pointed to, I get the error:
A first chance exception of type 'System.NullReferenceException' occurred
in PInvokeTest.exe Additional information: Object reference not set to an
instance of an object.
What could be causing this? In this tutorial on Pinvoke, the author quotes an MSDN article that says:
...the application is responsible for somehow extending the lifetime of
the delegate until no more calls will occur from unmanaged code...
Could this be the problem? If it is, I'm not sure how to make sure the lifetime of the delegate is long enough.
Currently, I define the following in a class (the delegate is named myCalllback
)
private static MyCallback _callbackInstance;
and pass it to C++ in a class method with the following:
_callbackInstance = new MyCallback(CallbackFunction);
setCallback(_callbackInstance);
where CallbackFunction
is a static function, and setCallback is a static extern
function.