简体   繁体   English

垃圾收集器会删除导出到C#的C ++类吗?

[英]Will be C++ classes exported to C# deleted by the garbage collector?

The idea is to create and export a wrapper for the C++ class and then use it from C# like following: 这个想法是为C ++类创建和导出一个包装器,然后从C#中使用它,如下所示:

First, let us create the C++ class itself: 首先,让我们创建C ++类本身:

File : MyClass.cpp 档案:MyClass.cpp

class myclass
{
public:

    int funct(int val)
    {
       return val + 1;
    }

 ~myclass(){}
};

Then, we create a wrapper: 然后,我们创建一个包装器:

File wrapper.cpp 文件wrapper.cpp

extern "C" __declspec(dllexport) myclass* expConst()
{
    return new myclass();
}

extern "C" __declspec(dllexport) void expDispose(myclass * obj)
{
    delete obj;
}

extern "C" __declspec(dllexport) int expfunct(myclass* obj, int val)
{   
    return obj->funct(val);
}

Now, we come to c#: 现在,我们来看看c#:

public class CsClass : IDisposable
{
    //Import the functions from dll

    [DllImport("ExportedLib.dll")]
    public static extern IntPtr expDispose(IntPtr obj);

    [DllImport("ExportedLib.dll")]
    public static extern IntPtr expConst();

    [DllImport("ExportedLib.dll")]
    public static extern int expfunct(IntPtr obj, int val);

    IntPtr objPtr;
    public CsClass()
    {
        objPtr = expConst();
    }

    public int funct(int q)
    {
        return expfunct(objPtr, q);
    }

    public void Dispose()
    {
        expDispose(objPtr);
    }
}

Finally, we ecxecute this by File:Program.cs 最后,我们通过File:Program.cs将其执行

class Program
{
    static void Main(string[] args)
    {
        CsClass v = new CsClass();
        Console.WriteLine(v.Func(1));
    }
}

I tested this simple things and the program printed 2 as it was expected. 我测试了这个简单的东西,程序按预期打印了2张。

The question is, whether the garbage collector of C# will move the created C++ object and, thus, making the objPtr to point to some wrong place in memory? 问题是,C#的垃圾回收器是否将移动创建的C ++对象,从而使objPtr指向内存中的某个错误位置?

Are there any other principal obstacles here? 这里还有其他主要障碍吗? I mean some unsolvable problems which make such an approach impossible. 我的意思是一些无法解决的问题,这些问题使这种方法无法实现。

Thanks in advance. 提前致谢。

No, the garbage collector only goes to work for managed memory. 不,垃圾收集器仅适用于托管内存。 Your class created in C++ is not managed memory and will not be touched, for good or for bad. 用C ++创建的类不是托管内存,无论好坏,都不会被触及。 You will need to manage it yourself as you already did. 您将需要像以前一样自行管理它。

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

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