简体   繁体   中英

Alloc array in C++ and free in C#

I write a programm that uses a 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传递回您的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. 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. This, then, depends on the library, so there is no generally correct answer.

Therefore, unless specified, there is no need for this.

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