2

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.

So basically, my C++/CLR method header is this:

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. 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.

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);
    ...
}
4

1 回答 1

6

使用pin_ptr<> 模板类来固定数组并生成本机代码可以使用的指针。固定它可确保在本机代码使用它时,垃圾收集器无法移动数组。

只需确保在 pin_ptr<> 变量超出范围后,本机代码不能再使用该数组。这也意味着存储指针供以后使用的本机代码是不行的。如果是这样,那么您必须制作副本。

于 2013-07-17T00:34:11.823 回答