'How to efficiently marshal array of objects to native function using C++/CLI

I have array of objects holding primitive types and enums; how do I marshal a pointer to this data to a native function with the signature native_func(void* ptr[]).

array<System::Object^>^ values = gcnew array<System::Object>(64);

// ... populate the managed array with primitives ...

// data is pinned and won't be moved by the GC
pin_ptr<object> pinned = &values[0]; 

// not sure what do here... data is corrupted in the native code
native_func((void**)pinned); 

Thanks!

EDIT. My second attempt was to do the following:

pin_ptr<object> pinned = &values[0]; 
void* testArray[64];
for (auto i = 0; i < values->Length; i++)
{
    testArray[i] = (void*)Marshal::UnsafeAddrOfPinnedArrayElement(values, i);
}
native_func(testArray);

Now, the addresses stored in testArray are getting passed correctly to the native side but the contents of the memory is not what I am expecting. What am I doing wrong now?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source