简体   繁体   中英

pInvoke C# DLLimport problem

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?

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

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