17

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) );
1
  • did you test this? can't you try it yourself and tell us how it goes? Commented Mar 8, 2011 at 16:49

2 Answers 2

37

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Yup. [MarshalAs] is not needed here, it is already assumed. The frame argument is either ref or IntPtr, not both.
seems like i had issues with crashes unless i put the [UnmanagedFunctionPointer(CallingConvenction.Cdecl)] Thank you
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);
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.