元素在C#字节数组和C ++字节数组之间 [英] Marshal between C# byte array and C++ byte array
问题描述
我有一个C#数组< System :: Byte>
,我想把它转换为C ++ byte *
。我该怎么办?我使用C ++ / CLR,因为它允许我在同一个项目中使用托管/非托管代码。我基本上写一个DLL和一些方法,可以通过C#调用,但包含非托管C ++代码。
I have a C# array<System::Byte>
and I want that to translate to a C++ byte*
. How can I do that? I am using C++/CLR because it lets me use managed/unmanaged code in the same project. I'm basically writing a DLL and making a few methods that can be called via C#, but that contain unmanaged C++ code.
基本上,我的C ++ / CLR方法头是这样的:
So basically, my C++/CLR method header is this:
void testMethod(array<Byte>^ bytesFromCSharp);
和 testMethod
将 bytesFromCSharp
转换为可以由其他非托管C ++代码使用的字节*
。我修改了 byte *
数组,并写了一个for循环逐个字节复制,但感觉就像应该有一个更好的解决方案。
and inside of that testMethod
I would like to translate the bytesFromCSharp
into a byte*
which can be used by other unmanaged C++ code. 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.
编辑:他的技巧范例从他的回答如下:
//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);
...
}
推荐答案
使用 pin_ptr<>模板类固定数组并生成本机代码可以使用的指针。固定它确保在本地代码使用它时,垃圾收集器不能移动数组。
Use the pin_ptr<> template class to pin the array and generate a pointer that native code can use. Pinning it ensures that the array cannot be moved by the garbage collector while the native code is using it.
只要确保本地代码不能使用数组后pin_ptr<>变量超出范围。这也意味着本地代码存储指针供以后使用不是好。如果是的话,您 有权复印。
Just make sure that the native code cannot use the array anymore after the pin_ptr<> variable goes out of scope. 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.
这篇关于元素在C#字节数组和C ++字节数组之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!