简体   繁体   中英

Free C allocated memory in C#

I have tons of C code that I need to use in C#. Example:

long foo(char** mystring);
void free_string(char* mystring);

foo() is using malloc() to allocate memory for mystring . I have tried several ways of calling this function from C#, but I am failing to free mystring . Can you please give me some guidelines on how to call foo() so that I can later free mystring ?

For example, if char** is represented by StringBuilder[] , then how can I use it to be freed in free_string() ?

Allocating memory in native to be freed in managed puts quite an overhead on ensuring the caller knows exactly what they are doing, You might want to consider other techniques for allocating the memory in managed code.

One example might be to make a callback into the managed code to get a string buffer

extern "C" __declspec void GetString( char* buffer, int bufferSize );

Matching C# would be the following:

void GetString( StringBuilder buffer, int bufferSize );

If you allocate memory using LocalAlloc in kernel32.dll then you could free it using Marshal.FreeHGlobal(IntPtr) . Though you can't free malloc'ed memory with it.

As another solution consider passing C# StringBuilder reference and fill it with C code.

Also take a look at MSDN article on memory models .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM