Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PInvoke C#: Function takes pointer to function as argument

Tags:

c#

pinvoke

param

I'd like to access this function in my c# code, is this possible? so in the end the c++ code would call my function and also apply the struct called "sFrameofData".

C++ Code:

//The user supplied function will be called whenever a frame of data arrives.
DLL int Cortex_SetDataHandlerFunc(void (*MyFunction)(sFrameOfData* pFrameOfData));

Would this work perhaps?

C# Code:

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(ref IntPtr function(ref IntPtr pFrameOfData) );
like image 957
Tistatos Avatar asked Mar 08 '11 16:03

Tistatos


2 Answers

You want to use a delegate that matches the method signature of your "MyFunction" C++ method.

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyFunctionDelegate(IntPtr frame);

[DllImport("Cortex_SDK.dll")]
public extern static int Cortex_SetDataHandlerFunc(
[MarshalAs(UnmanagedType.FunctionPtr)]MyFunctionDelegate functionCallback);
like image 134
ahawker Avatar answered Sep 21 '22 20:09

ahawker


I am not sure what is the proper way but I don't think is enough to use ref IntPtr for functions and structures...

see here for some help: C# P/Invoke: Marshalling structures containing function pointers

like image 41
Davide Piras Avatar answered Sep 23 '22 20:09

Davide Piras