将C#byte []传递给C ++作为无符号字符[] [英] Pass C# byte[] to C++ as Unsigned Char[]
问题描述
拥有C#字符串包含十六进制值,并且需要将其传递给接受unsigned char []的C ++ / CLI方法。我怎样才能传递这些信息。
我试图将字符串转换为C#byte []然后将其传递给c ++,但只传递了数组的第一个元素。 br $>
C#
Having a C# string contains hexadecimal value and required to pass it to C++/CLI method that accept unsigned char[]. How can I pass that information.
I tried to convert the string into C# byte [] and then pass it to c++ but only first element of array is passed.
C#
byte[] Byte = StringToByteArray(Data);
unsafe
{
byte* _passData;
fixed (byte* p = Byte)
{
_passData = (byte*)p;
}
SCARem.set_briefprivdata(_passData);
}
C ++
C++
void detdata(unsigned char _data[])
如果将字符串传递给c ++,然后将其转换为c ++中的unsigned char [],请分享更方便。
最终结果是C ++ unsigned char []。谢谢
Please share if passing an string to c++ and then converting it into unsigned char[] in c++ is more convenient.
End result required is C++ unsigned char[]. Thanks
推荐答案
我更喜欢Stringbuilder将字符串传递给C ++。请查看我的文章及其代码。
I prefer Stringbuilder for passing strings to C++. Take a look at my article and its code.
您可以使用带有.NET
String
的函数添加C ++ / CLI类,并调用detdata
功能。在该方法中,您可以使用 marshal_as 来转换字符串。类似于:
You can add a C++/CLI class with a function that takes a .NET
String
and call thedetdata
function. In that method, you can use marshal_as to convert the string. Something like:
#include <string>
#include <msclr\marshal_cppstd.h>
using namespace msclr::interop;
void detdata(unsigned char _data[]);
public ref class Class1
{
public:
Class1(void) {}
void f1(System::String^ str)
{
std::string data = marshal_as<std::string>(str);
detdata((unsigned char*)data.c_str());
}
};
然后,你可以使用 f1
函数在你的C#代码中。类似于:
Then, you can use the f1
function in your C# code. Something like:
Class1 c1 = new Class1();
c1.f1("Text 1");
c1.f1("Text 2");
c1.f1("Text 3");
谢谢你们这样做了。使用下面提到的代码。
Thanks guys its done. Using below mentioned code.
void Convert(String^ Data)
{
unsigned char array[28];
array<String^>^ strArray = gcnew array<String^>(28);
strArray = Data->Split(',');
int val = 0, index = 0;
for each (String^ value in strArray)
{
val = int::Parse(value);
array[index] = val;
index++;
}
}
这篇关于将C#byte []传递给C ++作为无符号字符[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!