In C i have the following functions
uint8_t* allocateMem() {
return malloc(4096);
}
void freeMem(uint8_t* ptr) {
free(ptr);
}
and in C# code
[DllImport(memDllPath, CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr allocateMem();
[DllImport(memDllPath, CallingConvention = CallingConvention.Cdecl)]
static extern void freeMem(IntPtr ptr);
and am using it as under
var mem = allocateMem();
var bytes = new byte[4096];
Marshal.Copy(mem, bytes, 0, 4096);
freeMem(mem); // is this ok?
My question is when I call freeMem again with the IntPtr will the memory (4096 bytes) that was allocated in C be freed?
Is there a guarantee to that? Are there any chances of memory leak with this pattern?
Trying to calling C functions from C#. I want to confirm if the pattern I have used in code is correct.
>Solution :
Yes this is the correct way to do this.
See this post for reference Just what is an IntPtr exactly?
It would be best to wrap such uses of unmanaged resources in RAII pattern Implementing RAII in C#