0

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?

TemaTre
  • 1,422
  • 2
  • 12
  • 20
  • 5
    just don't do that! if you need memory allocated from a dll, delete this memory in the dll. – user1810087 Aug 22 '14 at 10:42
  • See this question: http://stackoverflow.com/questions/25341441/declare-function-which-its-return-is-2-point-from-c-dll-in-c/25365087#25365087 – Alovchin Aug 22 '14 at 10:54

3 Answers3

3

Pass the IntPtr back to your dll so it can free the memory for itself.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Thanks, and another question. If I want to return char* from method (C style string). In C++ I create a std::string with xml, and return xmlString.c_str(); This is works but I can't understand why? If I create a variable in method (for examle xmlString), after return from method, this varialble will removed from stack and destructor will called(and char* that incapsulated in std::string will free ). If I correct understand this pointer is not valid? Here is another example: I create a local variable std::vector values; and do something, then I return &values[0]? – TemaTre Aug 25 '14 at 09:48
  • @TemaTre You may want to post another question, that's too much too explain in a comment. – nvoigt Aug 25 '14 at 10:04
2

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);
}
ikh
  • 10,119
  • 1
  • 31
  • 70
0

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.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53