将System::Byte的锯齿数组转换为无符号char**

convert jagged array of System::Byte to unsigned char**

本文关键字:转换 char 数组 无符号 System Byte      更新时间:2023-10-16

我想实现一个c++ CLI函数,将System::Byte的锯齿数组转换为无符号char**。我做了这个:

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

我目前无法测试,也许有人可以帮助我,告诉我是否可以,因为我需要它相对较快。谢谢你!

不行。这会以不同的方式出现在你面前:

unsigned char**     NUANCECLR::IsItYou::convertBBtoCC(array<array<System::Byte>^>^ b)
{
    unsigned char** x = NULL; 

未分配存储。x[anything]将无效。

    for (size_t indx = 0; indx < b->Length; indx++)
    {       
            if (b[indx]->Length > 1)
            {
                pin_ptr<System::Byte> p = &b[indx][0]; 

这个固定指针将在if块结束时超出作用域并解除固定。系统可能会再次随意移动或删除

                unsigned char* pby = p;

这将获取一个指向围绕一个字节的对象waappers数组的指针,并将其赋值给一个char数组。我不会在这里声称自己是专业人士,但我不相信如果没有很多隐藏的巫术,这将无法透明地工作。

                char* pch = reinterpret_cast<char*>(pby);

这将实际工作,但因为前面的可能没有,我不希望pch指向任何有意义的东西。

                x[indx] = reinterpret_cast<unsigned char *>(pch);

如上所述,x不指向任何存储。这是注定的。

            }
            else
                x[indx] = nullptr;

也注定

    }
    return x;

仍然注定失败。

}

推荐:

    为大小为b->Lengthchar *数组分配new的非托管存储,并分配给x
  1. 为大小为b[indx]->Lengthchar数组分配new的非托管存储,并复制b的所有元素到其中,然后分配给x[indx]
  2. 返回x
  3. 确保xx指向的所有数组在完成后都被删除。或者使用vector<vector<char>>代替char**