[英]C# C++/CLR handling ref parameters and string pointers
I'm consuming a C++/CLR DLL to my C# app and been struggling with passing byRef arguments to the native methods, as the Native code comes with "&" but the C# prompts I need to remove the "ref" (or "out") keyword. 我正在使用一个C ++ / CLR DLL到我的C#应用程序中,并努力将byRef参数传递给本机方法,因为本机代码带有“&”,但是C#提示我需要删除“ ref”(或“ out”)。 “)关键字。 Moreover, the arguments are translates to " " in my C# and strings for eg cannot accept that type so I'm getting conversion error from 'string' to 'string '.
此外,参数在我的C#中转换为“ ”,并且例如的字符串无法接受该类型,因此我收到了从“字符串”到“字符串 ”的转换错误 。
I'm using Pavel Yosifovich example code for this demo: 我为此演示使用了Pavel Yosifovich示例代码:
Managed C++ file: ManagedPerson.cpp 托管的C ++文件:ManagedPerson.cpp
String^ ManagedPerson::SayHello(String^ &greet) {
marshal_context ctx;
return gcnew String(m_pNative->SayHello(ctx.marshal_as<LPCTSTR>(greet)));
} }
My C# App: Main.cs 我的C#应用程序:Main.cs
static void Main(string[] args)
{
var person = new ManagedPerson("Bart", 10);
Console.WriteLine(person.SayHello("Hello "));
}
Then I'm getting this error in my C# compilation (cause of person.SayHello): 然后我在C#编译中遇到此错误(是person.SayHello的原因):
Argument 1: cannot convert from 'string' to 'string*'
This works if I remove the "&" from the C++ code (String^ &greet) but I must send it by reference. 如果我从C ++代码(字符串^&greet)中删除了“&”,但我必须通过引用将其发送,这将起作用。
I've managed to use types like Int32 using IntPtr successfully (though as unsafe code) but the problem is with strings and other complex types. 我已经成功使用IntPtr成功使用了类似Int32的类型(尽管这是不安全的代码),但是问题出在字符串和其他复杂类型上。
Any clue will help. 任何线索都会有所帮助。 Thx.
谢谢。
Ok this has been solved this way: 好的,这已经通过以下方式解决了:
When my string ref params in C++ code was like Foo(String^ MyStr) ,my CLR was expecting it as string*. 当我的C ++代码中的字符串引用参数像Foo(String ^ MyStr)时,我的CLR期望它为string *。
I had to call it like String^ % in order to call it in regular Foo(ref string MyStr) 我必须像String ^ %一样调用它,以便在常规Foo中调用它(参考字符串MyStr)
However, the MANAGED class wont pass the values to the ref params so I had to use temp params, ie: 但是,MANAGED类不会将值传递给ref参数,因此我不得不使用temp参数,即:
Void Foo(String^ %MyStr)
{
marshal_context ctx;
std::wstring temp_MyStr = ctx.marshal_as<std::wstring>(MyStr);
myCppClass->DoSomthing(temp_MyStr);
MyStr = temp_MyStr.c_str();
}
This refers also to other types such as int%, short% etc. 这也指其他类型,例如int%,short%等。
As for the example in the question, the solution was just replacing the "&" with "%". 对于问题中的示例,解决方案只是将“&”替换为“%”。
String^ ManagedPerson::SayHello(String^ %greet) {
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.