user610650
user610650

Reputation:

Does the memory of a string pointed to by an IntPtr returned by a DllImport need to be manually freed?

I have a couple of questions regarding the following:

[DllImport("libmp3lame.dll", CharSet = CharSet.Ansi)]
static extern IntPtr get_lame_version();

public static string GetLameVersion()
{
    IntPtr pVersion = get_lame_version();
    string version = Marshal.PtrToStringAnsi(pVersion);
    return version;
}
  1. Where is the memory of the string pointed to by pVersion allocated?
  2. Is this memory automatically freed when pVersion goes out of scope?
  3. If yes, how does that happen?
  4. If no, how do I free the memory?

Upvotes: 1

Views: 159

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

The string returned by this function is statically allocated and you do not need to free that memory. This means that your current code is already exactly what you need.

This is an open source project and so a websearch leads to the source code for the implementation of this function to confirm this.

As an aside, your p/invoke is incorrect, although it is benign. It should be:

[DllImport("libmp3lame.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr get_lame_version();

There's no need to specify CharSet since the function has no text parameters. And in any case Ansi is the default so you still would not need to specify that. The calling convention is, in general, important and will need to be set for all your LAME imports. It doesn't actually matter for a function with no parameters, but specifying the calling convention is a good habit to get in to.

Upvotes: 3

Related Questions