Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中将字符*编组到StringBuilder#_C#_C_Pinvoke - Fatal编程技术网

C# 在C语言中将字符*编组到StringBuilder#

C# 在C语言中将字符*编组到StringBuilder#,c#,c,pinvoke,C#,C,Pinvoke,我知道这一点已经讨论过了,但3天后我还不明白为什么在调用C#中封装在DLL中的C函数后会一直得到一个空字符串: 大体上: StringBuilder rsComment = new StringBuilder(256); apiWrap.QA_FormatExample(currentInstance, viExample, rsComment); System.Diagnostics.Debug.WriteLine(rsComment); 职能部门的签名: int __stdcall QA_

我知道这一点已经讨论过了,但3天后我还不明白为什么在调用C#中封装在DLL中的C函数后会一直得到一个空字符串:

大体上:

StringBuilder rsComment = new StringBuilder(256);
apiWrap.QA_FormatExample(currentInstance, viExample, rsComment);
System.Diagnostics.Debug.WriteLine(rsComment);
职能部门的签名:

int __stdcall QA_FormatExample(int, int, char*);

函数
QA_FormatExample
在调用后初始化
rsComment
,但我一直得到
rsComment
空白。任何建议都将非常感谢,谢谢。

< P>为了匹配C++,函数应该声明如下:

[DllImport(DllName)]
public static extern int QA_FormatExample(
    int viHandle, 
    int viExample,
    StringBuilder rsComment
);
StringBuilder comment = new StringBuilder(256);
int res = QA_FormatExample(handle, example, comment);
你这样称呼它:

[DllImport(DllName)]
public static extern int QA_FormatExample(
    int viHandle, 
    int viExample,
    StringBuilder rsComment
);
StringBuilder comment = new StringBuilder(256);
int res = QA_FormatExample(handle, example, comment);
这与你在问题中提出的非常接近。因此,如果对函数的调用不起作用,那么问题在于我们看不到的代码。我在上面展示的是通过
char*
将文本从本机封送到托管的正确方法


我要指出的是,不将缓冲区的长度传递给函数有点不寻常。如果没有该信息,则必须对最大长度进行硬编码

它是否在C代码中明确设置?C函数是如何导出的?C默认为
cdecl
调用约定,C默认为
stdcall
——如果您没有在C函数中指定
\uu stdcall
作为调用约定,那么您必须在
DllImport
装饰中指定
调用约定.cdecl
。谢谢你们的回答。Rughes-是的,C代码明确设置了“rsComment”,这是我公司的一个产品的API函数,所以它已经过测试。J-C函数的完整签名是:u declspec(dllimport)int u stdcall QA_FormatExample(int,int,char*),因此它已经指定为“stdcall”。@user3215290-请将其添加到问题中。