Callback function from c++ DLL
I have found many examples that I thought may help but I cannot get my head around callback functions from the c++ DLL.
I have the following code
global.cs
Code:
[DllImport("my.dll")]
unsafe public static extern UInt16 RegisterDetectCallback(void* detectCallbackFunction);
In my own code I have tried a few things but basically want the following functionality
program.cs
Code:
public void DetectCallback()
{
// some functionality...
}
private void button1_Click(object sender, EventArgs e)
{
//various code...
UInt16 result = DLLFunctions.RegisterDetectCallback(DetectCallback());
}
I have tried a few things without success, can anybody point me in the right direction please? i know the above is incorrect as the DLL requires a pointer and i'm trying to pass a function, but hopefully the intention is clear.
Also is it possible to do this without unsafe code? without changing the c++, or is this a requirement when passing functions as parameters in this way?
Thanks
Matt
Re: Callback function from c++ DLL
I don't have a ton of experience in this realm, but you just cannot get a pointer without going into unsafe code (not the same as a reference). Your code is not passing in anything at all. I think that you will need to go into an unsafe context here, which isn't really bad if you know what you are doing.
Re: Callback function from c++ DLL
I have fixed my code thanks to the link in another thread 'interop of native c...'
The working code is:
global.cs
Code:
public delegate void DetectCallback();
[DllImport("my.dll")]
unsafe public static extern UInt16 RegisterDetectCallback(DetectCallback myDetectCallback);
program.cs
Code:
public void myDetectCallback()
{
// some functionality...
}
private void button1_Click(object sender, EventArgs e)
{
//various code...
UInt16 result = DLLFunctions.RegisterDetectCallback(myDetectCallback);
}
Thanks,
Matt