[英]How to return a string from native code to managed code in Windows Azure?
I have found this tutorial about how to interop C# code and unmanaged C++ code on Windows Azure very helpful http://msdn.microsoft.com/en-us/hh351534 I have found this tutorial about how to interop C# code and unmanaged C++ code on Windows Azure very helpful http://msdn.microsoft.com/en-us/hh351534
However when I modify it, I run into some unforeseen errors.但是,当我修改它时,我遇到了一些无法预料的错误。
Instead of returning and displaying an int
from unmanaged code, I would like it to return a string an display that string in C# code.我希望它返回一个字符串,而不是从非托管代码返回和显示一个
int
,并在 C# 代码中显示该字符串。 So in my experiment, I changed the function AddNumbers()
from所以在我的实验中,我将 function
AddNumbers()
从
NATIVECALCULATOR_API int AddNumbers(int left, int right){
return left+right;
}
into进入
NATIVECALCULATOR_API char *AddNumbers(int left, int right){
return "a string";
}
so that when I hit the button on ASP.NET page, it will return "a string".这样当我点击 ASP.NET 页面上的按钮时,它将返回“一个字符串”。
However, in default.aspx.cs, the web page codebehind file, it tells me I can't change但是,在 default.aspx.cs,web 页面代码隐藏文件中,它告诉我无法更改
static extern int AddNumbers(int left, int right);
into进入
static extern char *AddNumbers(int left, int right);
because "pointers can only be used in unsafe context"因为“指针只能在不安全的上下文中使用”
And from there I have tried many methods, but I am unable to convert AddNumbers()
into a string to display.从那里我尝试了很多方法,但我无法将
AddNumbers()
转换为要显示的字符串。
So basically, can someone show me how to modify the tutorial to display a string instead of a int.所以基本上,有人可以告诉我如何修改教程以显示字符串而不是 int。
What C# is trying to tell you is that it won't let you use raw pointers willingly. C# 试图告诉你的是它不会让你心甘情愿地使用原始指针。 Thankfully we can still pass strings (even raw char strings) from unmanaged code to managed code through Data Marshalling.
值得庆幸的是,我们仍然可以通过数据编组将字符串(甚至是原始字符字符串)从非托管代码传递到托管代码。 In the case of strings, the system translates a
char*
in C++ to a string
in C#.对于字符串,系统将 C++ 中的
char*
转换为 C# 中的string
。
For your specific question, change AddNumbers
in default.aspx.cs from对于您的具体问题,将 default.aspx.cs 中的
AddNumbers
从
static extern int AddNumbers(int left, int right);
to至
static extern string AddNumbers(int left, int right);
Likewise, change the C++ code to read like so同样,将 C++ 代码更改为如下所示
NATIVECALCULATOR_API char* AddNumbers(int left, int right)
{
return "a string";
}
The data marshalling should correctly pass the string from one to the other.数据编组应该正确地将字符串从一个传递到另一个。
Here's the MSDN article that explains data marshalling in (MUCH) more detail.这是 MSDN 文章,它更详细地解释了数据编组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.