NullReferenceException during C++ callback to C# function

后端 未结 1 624
野趣味
野趣味 2021-01-18 07:51

developers!
I have very strange problem. My project has DLL writen in C++ and a GUI writen in C#. And I have implemented callback for some interoperability. I planed tha

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 08:33

           SetDelegate(new WriteToConsoleCallback(PrintSymbol));
    

    Yes, this cannot work properly. The native code is storing a function pointer for the delegate object but the garbage collector cannot see this reference. As far as it is concerned, there are no references to the object. And the next collection destroys it. Kaboom.

    You have to store a reference to the object yourself. Add a field in the class to store it:

        private static WriteToConsoleCallback callback;
    
        static void Main(string[] args)
        {
            InitializeLib();
            callback = new WriteToConsoleCallback(PrintSymbol);
            SetDelegate(callback);
            // etc...
        }
    

    The rule is that the class that stores the object must have a lifetime at least as long as native code's opportunity to make the callback. It must be static in this particular case, that's solid.

    0 讨论(0)
提交回复
热议问题