hey all im trying to get my head around calling this c++ function in c#:
BOOL __stdcall CodecStart(int hRadio,void __stdcall (*CallbackFunc)(void *),void *CallbackTarget);
this is from a WinRadio api found here http://www.winradio.com/home/g305_sdk.htm.
i did find that other people asked about calling this specific function on the net and they had:
public delegate void CallbackFunc( IntPtr p);
[DllImport("WRG305API.dll")]
public static extern bool CodecStart(int hRadio, CallbackFunc func, IntPtr CallbackTarget);
but i cant figure out how to implement this further.
any thoughts or guidance as to how to call this?
many thanks
Here’s a simple implementation that will put it all together.
Note that because
MyCallbackFuncwill be executed on a different thread, I chose to make isstatic. This way you won’t be tempted to accessWinRadioWrapperdata members.For simplicity I passed an
IntPtr.Zeroparameter to the callback, but this can point to any data that you’d like to use in the callback.[Please ignore this paragraph] Look into
Marshal.StructureToPtrif you’d like to pass data to the callback, but make sure to also pin the data that you’re passing in order to make sure it’s not garbage-collected (seeGCHandlefor more details).EDIT:
With the interesting words by svick (thanks!), I realize I was mixing a copied object with a pinned one.
So, to sort things out:
Marshal.StructureToPtrshould be used if you want to copy an existing data structure and then pass it to the callback function.GCHandlein order to pin it in memory and prevent it from being garbage-collected.This, however, will add some maintenance overhead for the
GCHandle.