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 call C functions from C#. I want to confirm if the pattern I have used in code is correct.
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#
I'm not seeing the point in the need to use DllImport and C? If you're using C# you could just use these functions in C#.
using System.Runtime.InteropServices;
static IntPtr AllocateMem() => Marshal.AllocHGlobal(4096);
static void FreeMem(IntPtr mem) => Marshal.FreeHGlobal(mem);
This would help prevent the need for extra dependencies while providing better optimazation and memory management.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With