简体   繁体   中英

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?

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.

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