将托管C#中的字符串传递给托管C ++ [英] pass a string from managed C# to managed C++
问题描述
在C ++和C#之间传递字符串的首选方法是什么?
i有一个c ++类,其中一个函数采用const char * var1
和 const char * var2 []
作为参数。
当我在C#中调用这样的函数时,函数接受参数类型为sbyte *。
只是使用ac#-string似乎不起作用,因为C#中的函数需要sbyte *和sbyte **
C ++类:
what is the preferred method to pass a string between C++ and C#?
i have a c++ class where one of the functions takes a const char *var1
and const char* var2[]
as parameter.
When I call such function in C# , function accepts arguments types as sbyte*.
Just using a c#-string doesnt seem to work as the function in C# requires a sbyte* and sbyte**
C++ class:
public ref class MyClass
{
public:
void Sample(const char * var1,const char* Var2[]);
}
C#来电..
C# call..
class Program
{
static void Main(string[] args)
{
MyClass oClass = new MyClass();
string var1 = "Variable1";
string[] var2 = {"1","2"};
oClass.Sample(var1,var2);
}
}
错误:
Error:
Error 1 Argument 1: cannot convert from ''string'' to ''sbyte*''<br />
Error 2 Argument 2: cannot convert from ''string[]'' to ''sbyte**''
所以我需要帮助来理解如何将托管C#中的字符串参数传递给托管C ++?
谢谢
So I need help in understanding how can I pass string arguments from managed C# to managed C++?
Thanks
推荐答案
C#String是复杂的对象,所以你需要一个字符数组,其中有字符。
byte [] buffer = Encoding.ASCII.GetBytes(var1);
或使用Stringbuilder类
并注意正确的字节大小。
The C# String are complexe objects so you need a byte array in which the chars are.
byte[] buffer = Encoding.ASCII.GetBytes(var1);
or use the Stringbuilder class
And look out for the right byte size.
这篇关于将托管C#中的字符串传递给托管C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!