Using C DLL allocated memory in C# then destroying it.

  • Thread starter Thread starter H?seyin
  • Start date Start date
H

H?seyin

I'm calling a function from a C DLL in .NET(C#).

The func. seems so:

void Sample(char *s)
{
s= calloc(6,1);
strcpy(s, "hello");
}

When I declare this function in C# I use the following notation:
[DllImport("sample.dll", CharSet = CharSet.Ansi)]
public static extern void Sample(out StringBuilder s);

However when I look at the watch window when debugging I can't see s =
"hello". Instead s = null;
And then after using this variable I want to destroy the memory
allocated with calloc in C# side.

Can you help me to solve this problem.
 
I believe the problem you're having is because of teh Stringbuilder not
being initialized. You would need to create a StringBuilder oject and
pass it by value and it should work just fine.
HTH

H?seyin said:
I'm calling a function from a C DLL in .NET(C#).

The func. seems so:

void Sample(char *s)
{
s= calloc(6,1);
strcpy(s, "hello");
}

When I declare this function in C# I use the following notation:
[DllImport("sample.dll", CharSet = CharSet.Ansi)]
public static extern void Sample(out StringBuilder s);

However when I look at the watch window when debugging I can't see s =
"hello". Instead s = null;
And then after using this variable I want to destroy the memory
allocated with calloc in C# side.

Can you help me to solve this problem.
 
void Sample(char *s)
{
s= calloc(6,1);
strcpy(s, "hello");
}

If you want to return the string pointer you must add another level of
indirection

void Sample(char **s)
{
*s = (char*)calloc(6,1);
strcpy(*s, "hello");
}

And then after using this variable I want to destroy the memory
allocated with calloc in C# side.

You can't do that, you must free the memory in the C DLL.



Mattias
 
Thanks for help.
I have added another level of indirection to the function char *s->
char **s.
So I have been able to get the value "hello" from C DLL.

Why can't I free the memory in C#. I saw that C# has some functions
like Marshall.FreeHGlobal. Can they help me to free the memory in C#
side?

Regards,
Hüseyin Özkan
 
Why can't I free the memory in C#. I saw that C# has some functions
like Marshall.FreeHGlobal. Can they help me to free the memory in C#
side?

No, FreeHGlobal should only be used to free memory allocated with
LocalAlloc/GlobalAlloc. To free memory allocated with the CRT memory
functions you should use free() from the same CRT, which in general
isn't directly accessible from C#. You could of course export a
cleanup function from your DLL that simply wraps a call to free. Or
you could change allocation API in your Sample function and use for
example LocalAlloc instead.



Mattias
 
Back
Top