简体   繁体   English

pInvoke C#DLLimport问题

[英]pInvoke C# DLLimport problem

Im using P/invoke on an unmanaged dll function swe_get_planet_name() in C#. 我在C#中的非托管dll函数swe_get_planet_name()上使用P /调用。 The given function definition is, 给定的函数定义是,

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

This means the return value is assigned to char *spname? 这意味着将返回值分配给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 所以我的C#代码是

[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. 这执行没有错误,但是变量“名称”在每个项目中分配了一个毫无意义的“ \\ 0”,而不是应该返回的行星名称。 Nothing wrong with the DLL since the vendor provided sample app works smoothly. DLL没问题,因为供应商提供的示例应用程序运行流畅。 Any ideas? 有任何想法吗?

It looks a very weak and dangerous C interface, without a size parameter being passed. 它看起来非常脆弱且危险,没有传递size参数。

The normal pattern here is to provide a Stringbuilder to receive the text, and let the marshaler do it's magic. 此处的正常模式是提供一个Stringbuilder来接收文本,并让封送处理程序做到这魔术。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM