Search code examples
c#ccharmarshallingintptr

C# Free IntPtr from C malloc


I have an unmanaged DLL on C with func:

char* My_Func(char* data, int input_length, int output_length);

In this func i have

result = (char*)malloc(output_lenght);
strcpy(result,test_char);
return(result);

In C# i import it

[DllImport(@"libsmev.DLL", CharSet = CharSet.Ansi)]
public static extern IntPtr My_Func([MarshalAs(UnmanagedType.LPStr)]string data, int input_length, out int output_length);

And call it

IntPtr result = My_Func (n1, n1.Lenght,n2);

How to free char* or IntPtr?

Marshal.FreeHGlobal(IntPtr) and Marshal.FreeCoTaskMem(IntPtr) doesn`t work.


Solution

  • In C, something like this:

    void Free_Obj(char* obj) {
        free(obj);
    }
    

    In C#, something like this:

    [DllImport("libsmev.DLL")]
    public static extern void Free_Obj(IntPtr obj);
    

    And call it:

    IntPtr result = My_Func (n1, n1.Lenght,n2);
    Free_Obj(result);