androidbuddy
androidbuddy

Reputation: 304

Calling call back function of .NET application from processors C code

I have .NET application and C code in my board. .NET application will call C function (To watch button has pressed or not ?) with callback function as argument and end its task. My C application will watch the button and when the button is pressed callback function (of .NET) has to be called. How can I call that callback function (of .NET) from my C code ?

Upvotes: 0

Views: 67

Answers (1)

JaredPar
JaredPar

Reputation: 755457

On the C definition of your function the call back should be expressed as a function pointer. For simplicity lets assume the call back returns void and has no arguments.

void NativeMethod(void (*pCallback)(void)) { 
  ...
}

Once this code is invoked the C code will have a simple function pointer. It can invoke this when it pleases and it will transition into the .Net code.

On the .Net side we need to define both a delegate for the function pointer type and a PInvoke stub to use to call into the C code.

delegate void CallbackFunc();

[DllImport("the_native_dll")]
static extern void NativeMethod(
  [MarshalAs(UnmanagedType.FunctionPtr)] CallbackFunc cb)

Now the C# code can call into the native code via the NativeMethod function using standard delegates

Upvotes: 1

Related Questions