简体   繁体   English

C ++中的Alloc数组,C#中免费

[英]Alloc array in C++ and free in C#

I write a programm that uses a Dllimport. 我编写了一个使用Dllimport的程序。 It's interesting for me, if I need to alloc some memory and return pointer to C# as IntPtr, how to free it? 对我来说很有趣,如果我需要分配一些内存并以IntPtr的形式返回指向C#的指针,该如何释放它?

IntPtr传递回您的dll,以便它可以自己释放内存。

For one thing, DON'T DO THAT! 一方面, 不要这样做! You're destroying one of the biggest benefits of managed language - you have to manage resources yourself. 您正在破坏托管语言的最大好处之一-您必须自己管理资源。


Despite that, if you really need to this, you can. 尽管如此,如果您确实需要此功能,则可以。

First, the native dll must provide its own memory free function. 首先,本机dll必须提供其自己的无内存功能。 And, just use it! 而且,只需使用它!

The code may be like this: 代码可能像这样:

static class Program
{
    [DllImport("foo.dll")]
    private static IntPtr myfooalloc();
    [DllImport("foo.dll")]
    private static void myfoofree(IntPtr p);

    static void Main(String[] args)
    {
        IntPtr p = myfooalloc();
        // Do something
        myfoofree(p);
    }
}

Or, more safely: 或者,更安全:

IntPtr p = myfooalloc();
try
{
    // Do something
}
finally
{
    myfoofree(p);
}

In general, libraries will be designed such that you don't need to do these kind of things (allocate on one end, free on another). 通常,库的设计使您无需执行此类操作(在一端分配,在另一端自由分配)。 But there are exceptions, of course, and often then you'll need to use an OS API function for the allocation of the memory. 但是当然也有例外,然后通常需要使用OS API函数来分配内存。 This, then, depends on the library, so there is no generally correct answer. 然后,这取决于库,因此通常没有正确的答案。

Therefore, unless specified, there is no need for this. 因此,除非另有说明,否则无需这样做。

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

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