views:

43

answers:

1

Im using P/invoke on an unmanaged dll function swe_get_planet_name() in C#. The given function definition is,

char* swe_get_planet_name(int ipl, char *spname);

This means the return value is assigned to char *spname? It seemed so from the sample code in the documentation.

char snam[40];          
/*
 * get the name of the planet p
 */
swe_get_planet_name(p, snam);
/*
 * print 
 */
printf(snam);


So my c# code is

[DllImport("swedll32.dll")]
        private static extern void swe_get_planet_name(int ipl, char[] spname);

char[] name = new char[40]; 
int p = 3;
swe_get_planet_name(p, name);

This executes without error but variable 'name' is assigned a meaningless '\0' in each item instead of the planet name that it's supposed to return. Nothing wrong with the DLL since the vendor provided sample app works smoothly. Any ideas?

+4  A: 

It looks a very weak and dangerous C interface, without a size parameter being passed.

The normal pattern here is to provide a Stringbuilder to receive the text, and let the marshaler do it's magic.

[DllImport("swedll32.dll")]
private static extern void swe_get_planet_name(int ipl, StringBuilder spname);

//char[] name = new char[40]; 
StringBuilder name1 = new StringBuilder(40); // the 40 may be usefuul, not sure
int p = 3;
swe_get_planet_name(p, name1);
string name = name1.ToString();
Henk Holterman
I agree it's a bad interface but I don't think he can change it....
jdv
It is better to declare return type as IntPtr, since original function returns pointer.
Alex Farber
Thanks heaps guys. StringBuilder solution works!
smkngspcmn