0

When using a member function for a C-Style callback, is it necessary to pin the delegate so that it is not collected or moved by the GC? I have read several posts on the subject but have not been able to determine if it's necessary or the correct way of implementing.

public delegate void FeedCallbackDelegate(int type,void* data,void *param);

public ref class CStyleApiWrapper
{

    public:

    void StartFeed();

    private:

    FeedCallbackDelegate^ managedFeedCallback;
    IntPtr unmanagedFeedCallbackPtr;

    void FeedCallback(int code,int type,void* data,void *param);

};


void CStyleApiWrapper::StartFeed()
{

    managedFeedCallback = gcnew managedFeedCallback(this, &CStyleApiWrapper::FeedCallback);
    unmanagedFeedCallbackPtr = Marshal::GetFunctionPointerForDelegate(managedFeedCallback);

    //Start Feed
    StartFeed((NOTIFY_FUNC)(void*)unmanagedFeedCallbackPtr,0,NULL);

}

void CStyleApiWrapper::FeedCallback(int type,void* data,void *param)
{
    //Process Feed
    ...
}

1 Answer 1

1

Just calling GetFunctionPointerForDelegate is not enough to keep the GC from reclaiming your delegate. You have to Alloc a handle with GCHandle.Alloc on the delegate. Alloc adds a reference to the delegate, which prevents disposal. Then you have to Free that handle when you are done with it.

Here is a good example page: http://msdn.microsoft.com/en-us/library/367eeye0%28v=VS.100%29.aspx.

Sign up to request clarification or add additional context in comments.

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.