How to free memory allocated in C# to an IntPtr passed from C++ dll?

-1

A pointer is passed to me from a C++ dll as followed:

[DllImport("myfile.dll", EntryPoint = "LoadFile", SetLastError = true, CharSet = CharSet.None)]
public static extern IntPtr dLoadFile(string x);

IntPtr p = dLoadFile("myfile");

//Do things with p.

Marshal.FreeHGlobal(p) //crash on this line with exception below.

System.Runtime.InteropServices.COMException: 'One or more arguments are invalid (Exception from HRESULT: 0x80000003)'

Should I free the memory allocated to IntPtr ? And if yes, how to do it properly ? Obviously it seems that Marshal.FreeHGlobal() is not the way to go...

Thanks

c#
dll
marshalling
asked on Stack Overflow Feb 26, 2019 by bricx

1 Answer

0

The general rule is that "who allocates the resources needs to be called to perform the cleanup". In c#, you d not own the memory : the clr owns it. Your shared c# assemblies also share the clr, therfore you have the impression to create an object in one assembly and free it in another. When performing interoperability, a resource created by a library should be cleaned up by the same library via an additional exported api. There are some exceptions though, and they regard when operating systems objects are created :according to the specific documentation of the object in question, you can free the resource at caller site.

In your case, you should export the appropriate api in my file.dll that properly perform the cleanup.

This rule allows you not to disclose internal details, thus allowing you to change your internals without breaking the caller.

answered on Stack Overflow Feb 26, 2019 by Yennefer

User contributions licensed under CC BY-SA 3.0