简体   繁体   English

C#字节数组和C ++字节数组之间的元帅

[英]Marshal between C# byte array and C++ byte array

I have a C# array<System::Byte> and I want that to translate to a C++ byte* . 我有一个C# array<System::Byte> ,我希望将其转换为C ++ byte* How can I do that? 我怎样才能做到这一点? I am using C++/CLR because it lets me use managed/unmanaged code in the same project. 我正在使用C ++ / CLR,因为它允许我在同一项目中使用托管/非托管代码。 I'm basically writing a DLL and making a few methods that can be called via C#, but that contain unmanaged C++ code. 我基本上是在写一个DLL,并制作一些可以通过C#调用的方法,但其中包含非托管C ++代码。

So basically, my C++/CLR method header is this: 所以基本上,我的C ++ / CLR方法标头是这样的:

void testMethod(array<Byte>^ bytesFromCSharp);

and inside of that testMethod I would like to translate the bytesFromCSharp into a byte* which can be used by other unmanaged C++ code. 在该testMethod内部,我想将bytesFromCSharp转换为byte* ,其他非托管C ++代码可以使用。 I malloced the byte* array and wrote a for loop to copy byte by byte but it feels like there should be a better solution. 我分配了byte*数组,并编写了for循环以逐字节复制,但是感觉应该有更好的解决方案。

edit: Example of Hans' technique from his answer below: 编辑:汉斯的技术示例,从他的回答如下:

//C#
byte[] myBytes = {1,2,3,4};

//C++/CLI
void testMethod(array<byte>^ myBytes) {
    pin_ptr<byte> thePtr = &myBytes[0];
    byte* bPtr = thePtr;
    nativeCode(bPtr);
    ...
}

Use the pin_ptr<> template class to pin the array and generate a pointer that native code can use. 使用pin_ptr <>模板类可固定数组并生成本机代码可以使用的指针。 Pinning it ensures that the array cannot be moved by the garbage collector while the native code is using it. 固定它可以确保在本机代码使用该数组时,垃圾回收器无法移动该数组。

Just make sure that the native code cannot use the array anymore after the pin_ptr<> variable goes out of scope. 只要确保在pin_ptr <>变量超出范围后,本机代码就不能再使用该数组。 Which also means that native code storing the pointer for later use is not okay. 这也意味着存储指针以供以后使用的本机代码是不正确的 If it does then you have to make a copy. 如果是这样,则必须进行复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM