To Ascii转换错误

时间:2016-12-26 10:18:03

标签: c++-cli

#include "stdafx.h"
typedef unsigned char byte;
typedef unsigned char BYTE;
using namespace System::Runtime::InteropServices;
using namespace System;


public ref class CRsiComBase {
    public :
    static int ToAsciiHex(BYTE* pToBuf, BYTE* pFromBuf, int iStartingIndex, int         iLength);
    static int ToAsciiHex(cli::array<byte>^ baToBuf, cli::array<byte>^ baFromBuf, int iStartingIndex, int iLength);
    static cli::array<BYTE>^ hexTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    };
    int CRsiComBase::ToAsciiHex(BYTE* pToBuf, BYTE* pFromBuf, int iStartingIndex, int iLength)
    {
    BYTE* pOutBuf = pToBuf;
         for (int j = 0; j < iStartingIndex; j++)
         {
        *pOutBuf++ = pFromBuf[j];
         }
    for (int i = iStartingIndex; i < iLength; i++) {
    BYTE b = pFromBuf[i];
    BYTE hb = b >> 4;
    BYTE lb = b & 0x0F;
    *pOutBuf++ = hexTable[(int)hb];
    *pOutBuf++ = hexTable[(int)lb];
    }
    return static_cast<int>(pOutBuf - pToBuf); // Length of message in pToBuf;
    }

int CRsiComBase::ToAsciiHex(cli::array<byte>^ baToBuf, cli::array<byte>^ baFromBuf, int iStartingIndex, int iLength) {
    int iRtn = 0;

    int fromLength = sizeof(baFromBuf);
    IntPtr pFromBuf = Marshal::AllocHGlobal(fromLength);
    Marshal::Copy(baFromBuf, 0, pFromBuf, fromLength);
    BYTE* pbFromBuf = (BYTE*)pFromBuf.ToPointer();
    int toLength = sizeof(baToBuf);
    BYTE* pbToBuf = new BYTE[toLength];
    iRtn = ToAsciiHex(pbToBuf, pbFromBuf, iStartingIndex, iLength);
    Marshal::Copy(static_cast<IntPtr>(pbToBuf), baToBuf, 0, iLength * 2);
    Marshal::FreeHGlobal(pFromBuf);
    delete[] pbToBuf;
    return iRtn;
    }


int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
    cli::array<byte>^ fromArray = gcnew cli::array<byte>(8);
    fromArray[0] = 1;
    fromArray[1] = 2;
    fromArray[2] = 3;
    fromArray[3] = 4;
    fromArray[4] = 5;
    fromArray[5] = 6;
    fromArray[6] = 7;
    fromArray[7] = 8;
    cli::array<byte>^ toArray = gcnew cli::array<byte>(16);
    CRsiComBase::ToAsciiHex(toArray, fromArray, 0, 8);
    Console::WriteLine(L"{0}", toArray[0]);
    Console::WriteLine(L"{0}", toArray[1]);
    Console::WriteLine(L"{0}", toArray[2]);
    Console::WriteLine(L"{0}", toArray[3]);
    Console::WriteLine(L"{0}", toArray[4]);
    Console::WriteLine(L"{0}", toArray[5]);
    Console::WriteLine(L"{0}", toArray[6]);
    Console::WriteLine(L"{0}", toArray[7]);

    return 0;
    }

对于上述代码,我收到错误![Debug Error] 1

在上面的代码中我试图将Byte转换为AsciiHex。  我无法弄清楚为什么删除会导致堆损坏?  如果我删除删除它将在以后的部分导致异常  我在“delete [] pbToBuf”中收到错误;线!请帮我指出我做错了什么:(

1 个答案:

答案 0 :(得分:1)

sizeof paToBuf不是数组的大小。

使用Length方法获取数组的逻辑大小。