14

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) );
Tistatos
  • 641
  • 1
  • 6
  • 16

2 Answers2

34

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);
0xced
  • 25,219
  • 10
  • 103
  • 255
ahawker
  • 3,306
  • 24
  • 23
  • 1
    Yup. [MarshalAs] is not needed here, it is already assumed. The *frame* argument is either *ref* or IntPtr, not both. – Hans Passant Mar 08 '11 at 17:13
  • seems like i had issues with crashes unless i put the [UnmanagedFunctionPointer(CallingConvenction.Cdecl)] Thank you – Tistatos Mar 09 '11 at 15:53
  • 2
    I'd like to add that simply calling `Cortex_SetDataHandlerFunc(MyFunc)` where `MyFunc` is defined as `void MyFunc(IntPtr frame) {...}` isn't enough. `Cortex_SetDataHandlerFunc(MyFunc)` is essentially `Cortex_SetDataHandlerFunc(new MyFunctionDelegate(MyFunc))` and the anonymous delegate object `new MyFunctionDelegate(MyFunc)` can be sometimes disposed by GC before `MyFunctionDelegate` returns. In this case you need to create a delegate object explicitly to avoid it to be GCed: `var myDele = new MyFunctionDelegate(MyFunc); Cortex_SetDataHandlerFunc(myDele);` – felixh Aug 30 '17 at 03:05
  • Hi, I'm in similar situation where I have to pass method pointer in another method. I understood Marshaling part. how would you call this method now. – akshay dhule Nov 21 '17 at 22:44
1

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

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147