简体   繁体   English

将代码从C ++包装到C#时的内存管理

[英]Memory management when wrapping code from C++ to C#

I am trying to wrap my C++ code into C#. 我正在尝试将C ++代码包装到C#中。 I managed to export my functions to DLL and then import them from C#. 我设法将函数导出到DLL,然后从C#导入它们。

My problem is as follows: 我的问题如下:

In my C++ code I have a singleton which i create by using the "createInstance" function. 在我的C ++代码中,我有一个单例,该单例是使用“ createInstance”函数创建的。 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. 在导出到DLL的新newCreateInstance函数中,我仅调用旧的createInstance,然后返回一个空指针,指向我创建的单调实例。

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. 但是我认为当我从C#调用第二个函数(在调用第一个函数之后)时,我的单调实例已经从内存中删除了。 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). ps-我无法在C#上创建相同的类,因为我不知道它的实现(它也来自DLL / LIB文件)。 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上说明的 GC.KeepAlive

MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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