0

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()?

pdp11
  • 1
  • 3
  • 2
    How exactly are you calling the C code? Can we some example code of your attempt? Your question, in its current state is way too vague to be answered accurately. – Rohan Prabhu Feb 20 '12 at 09:18
  • 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, for example something like this http://stackoverflow.com/questions/8425501/how-can-i-pass-an-empty-string-buffer-that-can-be-written-to-from-native-to-c – dice Feb 20 '12 at 09:23
  • I tried to call the C code in several ways, but I am not confident with any of them. For example: I tried 'static extern long foo( [MarshalAs( UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr )] StringBuilder[] mystring);' I tried with 'IntPtr ptr' instead of 'StringBuilder' and the Marshal.FreeCoTaskMem(ptr). It does not work – pdp11 Feb 20 '12 at 09:31

2 Answers2

1

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 );
dice
  • 2,820
  • 1
  • 23
  • 34
0

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.

Community
  • 1
  • 1
Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35