I would like to implement a C++\CLI function that convert a jagged array of System::Byte to unsigned char**. I made this:
unsigned char** NUANCECLR::IsItYou::convertBBtoCC(array<array<System::Byte>^>^ b)
{
unsigned char** x = NULL;
for (size_t indx = 0; indx < b->Length; indx++)
{
if (b[indx]->Length > 1)
{
pin_ptr<System::Byte> p = &b[indx][0];
unsigned char* pby = p;
char* pch = reinterpret_cast<char*>(pby);
x[indx] = reinterpret_cast<unsigned char *>(pch);
}
else
x[indx] = nullptr;
}
return x;
}
I can't test it currently, maybe someone can help me, tell me if it is ok or not, because I need it relatively fast.Thank you!
Not OK. This will bow up in your face a number of different ways:
unsigned char** NUANCECLR::IsItYou::convertBBtoCC(array<array<System::Byte>^>^ b)
{
unsigned char** x = NULL;
No storage allocated. x[anything]
will be invalid.
for (size_t indx = 0; indx < b->Length; indx++)
{
if (b[indx]->Length > 1)
{
pin_ptr<System::Byte> p = &b[indx][0];
this pining pointer will go out of scope at the end of this if block and unpin. The system may once again move or delete at will
unsigned char* pby = p;
This takes a pointer to an array of object wappers around a byte and assigns it to an array of char
. I won't claim expertise here, but I don't believe this will work transparently without a lot of hidden voodoo.
char* pch = reinterpret_cast<char*>(pby);
This will actually work, but becasue the previous likely doesn't, I don't expect pch
to point at anything meaningful.
x[indx] = reinterpret_cast<unsigned char *>(pch);
As stated above, x
doesn't point at any storage. This is doomed.
}
else
x[indx] = nullptr;
also doomed
}
return x;
and still doomed.
}
Recommendation:
new
for a char *
array of size b->Length
and assign to x
new
for a char
array of size b[indx]->Length
and copy all of the elements of b
into it, then assign to x[indx]
.x
x
and then x
are deleted when you're done with them. Or use vector<vector<char>>
instead of char**
.