[Mono-devel-list] reading char * from extern function

dietmar dietmar at ximian.com
Thu May 22 04:27:40 EDT 2003


On Thu, 2003-05-22 at 09:31, md at mt.web.id wrote:
> situation:
> I have a C library. One of it's function is:
> 
> char * some_func(int param, const char * param2) {
>     char *retval = NULL;
>     ....
>     /* retval is modified */
>     retval = malloc (1024);
>     strcpy (retval, "abc");
>     ....
>     return retval;
> }
> 
> in C# I implement this
> [DllImport ("libname", EntryPoint="some_func")]
> static extern byte [] libname_some_func (int uid, byte [] program);
> 
> public static void cs_side ()
> {
>       string s = Encoding.UTF8.GetString (libname_some_func (0,"test"));
>       Console.WriteLine ("{0}", s);
> }
> 
> when I run the program, libname_some_func() always returns null to 
> GetString.
> Unhandled Exception: System.NullReferenceException: A null value was 
> found where an object instance was required
> in <0x001a5> 00 System.Text.UTF8Encoding:InternalGetCharCount 
> (byte[],int,int,uint,uint,bool,bool)
> in <0x0002a> 00 System.Text.UTF8Encoding:GetCharCount (byte[],int,int)
> in <0x00063> 00 System.Text.Encoding:GetChars (byte[])
> in <0x00014> 00 System.Text.Encoding:GetString (byte[])
> in <0x000d9> 00 T.Test:cs_side ()
> in <0x00019> 00 T.Test:Main ()
> 
> if I change byte [] to char [] like this:
> [DllImport ("libname", EntryPoint="some_func")]
> static extern char [] libname_some_func (int uid, byte [] program);
> 
> public static void cs_side ()
> {
>       StringBuilder sb = new StringBuilder ();
>       sb.Append(libname_some_func (0,"test"));
>       Console.WriteLine ("{0}", sb.ToString());
> }                                                                                                   
> it yields:
> <<<GC Warning: Out of Memory!  Returning NIL!
> Trace/breakpoint trap
> 
> the value of retval in some_func() exists as I can prove it by doing 
> fprintf(stderr,">>>%s<<<", retval) just before it returns;
> 
> so the question is simple: how do I get a char * from c functions in C#?
> the next question is: should I free() the retval? if yes, how to do 
> that?

You can use "string" as return type:

[DllImport ("libname", EntryPoint="some_func")]
static extern string libname_some_func (int uid, byte [] program);

I guess the runtime should free the string for you, but we don't do that
currently. Somebody should test how MS handles this.

- Dietmar





More information about the Mono-devel-list mailing list