Function Pointer Call

I need to pass a managed callback to an unmanaged TCP receiver. Since this is a thread that must exist throughout the life of the application, I need to prevent it from garbage collection. I read everywhere that binding function pointers is not required, and GCHandle.Alloc will do the task of preventing garbage collection.

But is this given? I saw that the AppPool that hosts this code crashes with access violation. Why should I not suspect that this error occurs because the function pointer was garbage collected?

This post supports this fact.

Update: This appears to have significantly reduced the number of crashes. Is there a problem with this approach?

typedef void (__cdecl *ProcMessageFunc)(void* param, void* paramBuf, ULONG bufSize); FuncDelegate^ fp = gcnew MessageFuncDelegate(this, &Handler); pin_ptr<MessageFuncDelegate^> pinnedFunctionPointer = &fp; ret = Receiver ((ProcMessageFunc)pinnedFunctionPointer); 
+8
c # interop c ++ - cli
source share
1 answer

I am doing exactly what you are proposing to do - GCHandle.Alloc on the delegate, but without binding - and had no problems in widespread use on many different platforms and in versions of .NET 2.0 - 4. Something like:

  DelegateHandle = GCHandle.Alloc(xlDelegate); FunctionPointer = Marshal.GetFunctionPointerForDelegate(xlDelegate); 

with FunctionPointer then passed to native code, and DelegateHandle is for subsequent cleanup.

This seems to be the best link: http://msdn.microsoft.com/en-us/library/367eeye0(v=vs.80).aspx .

Nothing that you specify to contradict this link - you need to protect the delegate from garbage collection, it just is not required so that the commit is not required.

+8
source share

All Articles