Convert between IVector <T> ^ and C byte array in winrt component
My generic storage project for Windows 8.1 and Windows Phone 8.1 (C #) uses a Windows Runtime (C ++) component, which consists of a C library and a C ++ / CX wrapper class that provides access to C code for the winrt environment ...
I am passing byte arrays from C # code to component and receiving byte arrays using an interface IVector<unsigned char>^
. So, I need to convert back and forth between IVector
and C-style array unsigned char
.
This is how I do it now:
unsigned char *Component::CopyToArray(IVector<unsigned char>^ source)
{
unsigned char *target = new unsigned char[source->Size];
for (unsigned int i = 0; i < source->Size; i++) {
target[i] = source->GetAt(i);
}
return target;
}
Vector<unsigned char>^ Component::CopyToVector(unsigned char *source, unsigned int length)
{
Vector<unsigned char>^ target = ref new Vector<unsigned char>();
for (unsigned int i = 0; i < length; i++) {
target->Append(source[i]);
}
return target;
}
Is there a way to avoid memory allocation and data copying?
UPDATE : I realized it was CopyToVector
deprecated because there is a constructor that takes a pointer.
ref new Vector<unsigned char>(pointer, size)
UPDATE AND SOLUTION
I changed the code to use the public api of the C ++ wrapper class const Platform::Array<unsigned char>^
for the parameter types and Platform::Array<unsigned char>^
for the return types. C # sees these types as byte[]
, so there is no need for an explicit conversion. And in C ++, a unsigned char *
pointer is as easy to access as argOfArrayType->Data
. To return data from C ++ to C # I am using ref new Array<unsigned char>(pointer, size)
.
source to share
My experience with C ++ / CX is limited to a few applications, but why not use Platform :: WriteOnlyArray instead of Vector? With an array, you can access data directly through a property Data
. So the direction C # -> C ++ / CX can be optimized this way. It also has a constructor Array(T* data, unsigned int size)
which should help towards C ++ / CX -> C #. However, I'm not sure about memory management in this case, if the array is wrapping or copying data. And if he completes it, how does he know how to free it?
source to share