简体   繁体   中英

Memory management when wrapping code from C++ to C#

I am trying to wrap my C++ code into C#. I managed to export my functions to DLL and then import them from C#.

My problem is as follows:

In my C++ code I have a singleton which i create by using the "createInstance" function. In my new newCreateInstance function which I export to the DLL I just call the old createInstance and then return a void pointer pointing the singletone instance which I have created.

In other function I try to operate on the singletone instance. So, I get a void pointer, which I then cast to the relevant pointer, then try to operate on it.

But i think that when I call the second function (after calling the first) from C# my singletone instance is already been erased from memory. How do i keep the instance on my heap/stack? is it even possible or should i do it differently?

ps - I can't create same class on C# cause i don't know it's implementation (It also comes from a DLL/LIB file). So i have to use void pointers.

Thanks!!!

If your assumptions are correct about premature garbage collection, you need to use GC.KeepAlive as explained on MSDN :

MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM