Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# to C interop and memory allocation

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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#

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading