为什么这个显式 P/Invoke 不起作用?
以下 .net 到本机 C 代码不起作用,有什么想法
extern "C" {
TRADITIONALDLL_API int TestStrRef( __inout char* c) {
int rc = strlen(c);
std::cout << "the input to TestStrRef is: >>" << c << "<<" ;
c = "This is from the C code ";
return rc;
}
}
[DllImport("MyDll.dll", SetLastError = true)]
static extern int TestStrRef([MarshalAs(UnmanagedType.LPStr)] ref string s);
String abc = "InOut string";
TestStrRef(ref abc);
此时 Console.WriteLine(abc) 应该打印“This is from the C code”但没有,对问题有什么想法吗?
仅供参考 - 我有另一个不使用引用类型字符串的测试函数,它工作得很好
The following .net to native C code does not work, any ideas
extern "C" {
TRADITIONALDLL_API int TestStrRef( __inout char* c) {
int rc = strlen(c);
std::cout << "the input to TestStrRef is: >>" << c << "<<" ;
c = "This is from the C code ";
return rc;
}
}
[DllImport("MyDll.dll", SetLastError = true)]
static extern int TestStrRef([MarshalAs(UnmanagedType.LPStr)] ref string s);
String abc = "InOut string";
TestStrRef(ref abc);
At this point Console.WriteLine(abc) should print "This is from the C code " but doesn't, Any ideas on what's wrong ?
FYI - i have another test function not using ref type string, it works just fine
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的C端代码也错了。 __inout 注释只是告诉编译器您可以更改“c”参数指向的缓冲区。但是指针本身位于堆栈中,如果您修改了“c”参数,则指针本身不会返回给调用者。
您的声明可能如下所示:
C# 方面:
Your code wrong at C side also. __inout annotation just tell compiler you can change buffer to which "c" argument pointed. But pointer itself located in stack and does not return to caller if you modified "c" argument.
Your declaration may look like:
And C# side:
这对你有用吗?基本上只需添加 CallingConvention = CallingConvention.Cdecl到 DllImport 语句。您可能还想指定 CharSet(例如:CharSet:=CharSet.Unicode)
Does this work for you? Basically just add CallingConvention = CallingConvention.Cdecl to the DllImport statement. You might also want to specify the CharSet (for example: CharSet:=CharSet.Unicode)