Marshal between C# byte array and C++ byte array

2019-08-13 01:10发布

问题:

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

回答1:

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.

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++-cli