Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6926775
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T10:57:44+00:00 2026-05-27T10:57:44+00:00

Callbacks to C# from unmanaged C++ are tricky. I learned most of the required

  • 0

Callbacks to C# from unmanaged C++ are tricky.
I learned most of the required cruft from this
MSDN article
and this
stackoverflow tip,
and the result works fine in the debugger.
But outside of the debugger it fails with “Object reference not set to an instance of an object”.

Here’s the (simplified) C# code:

class CSharpCode
{
    delegate void CallbackDelegate();

    void DoCSharp()
    {
        CallbackDelegate callbackDelegate = TheCallback;
        IntPtr callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);
        GCHandle gchCallbackDelegate = GCHandle.Alloc(callbackDelegatePointer);

        GC.Collect(); // create max space for unmanaged allocations
        CppCliCode.DoCppCli(callbackDelegatePointer);
    }

    public static void TheCallback()
    {
        MessageBox.Show("It worked");
    }
}

And here’s the C++ code:

#pragma managed

public ref class CppCliCode
{
    static void DoCppCli(IntPtr^ callbackDelegatePointer)
    {
        callback theCallback = static_cast<callback>(callbackDelegatePointer->ToPointer());
        DoCpp(theCallback);
    }
}

#pragma unmanaged

typedef void (__stdcall *callback)();

void DoCpp(callback theCallback)
{
    theCallback();
}

The error occurs somewhere between invoking theCallback() and arriving at TheCallback(). The error suggests that some invisible managed object has become null.

If I remove the GC.Collect() the problem goes away. But that just means it will reappear someday as an intermittent mystery when a GC happens to occur at the wrong moment.

The GCHandle protects the delegate from being collected but allows it to be relocated. The MSDN article says “If a delegate is re-located by a garbage collection, it will not affect the underlaying managed callback, so Alloc is used to add a reference to the delegate, allowing relocation of the delegate, but preventing disposal. Using GCHandle instead of pin_ptr reduces fragmentation potential of the managed heap.”

What’s wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T10:57:45+00:00Added an answer on May 27, 2026 at 10:57 am

    You must allocate the delegate itself, not its IntPtr. Also you must free the GCHandle when you are done with CSharpCode instance.

    class CSharpCode : IDisposible
    {
        delegate void CallbackDelegate();
        GCHandle gchCallbackDelegate;
    
        void DoCSharp()
        {
            CallbackDelegate callbackDelegate = TheCallback;
            IntPtr callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);
            gchCallbackDelegate = GCHandle.Alloc(callbackDelegate); // !!!!
    
            GC.Collect(); // create max space for unmanaged allocations
            CppCliCode.DoCppCli(callbackDelegatePointer);
        }
    
        public void Dispose()
        {
            CleanUp();
        }
    
        ~CSharpCode()
        {
            CleanUp();
        } 
    
        CleanUp()
        {
            if(gchCallbackDelegate.IsAllocated)
                gchCallbackDelegate.Free();
        }
    
    
    }
    

    By the way I hope you have more powerful naming system of yours. Names like DoCSharp, TheCallBack, theCallBack etc. gave me a hard time to understand the question.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

From http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx it looks like, that this type of sockets are using more than
Is there any way to unregister callbacks from dojo.Deferred? If not why?
I'm working on a project that gets callbacks from some other sites' API. I
I have problem with callbacks from other application thread. Dll is some kind of
I have an object that receives callbacks from a boost::io_service , and for a
I've got a DOM tree I want to receive org.xml.sax.helpers.DefaultHandler callbacks from it. Is
Hi I am trying to call my managed call back callback , from unmanaged
Here's my code right now. I'm getting callbacks from Location manager, but it doesn't
My form receives asynchronous callbacks from another object on random worker threads. I have
I have a service that accepts callbacks from a provider. Motivation : I do

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.