2016-12-26 173 views
0
#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爲ASCII轉換錯誤

在上面的代碼我試圖字節轉換爲AsciiHex。 我無法確定爲什麼刪除導致堆損壞? 如果我刪除刪除它將導致在以後的部分 異常我收到錯誤在「刪除[] pbToBuf」;線!請幫我指點我在做什麼錯:(

回答

1

的sizeof paToBuf IST不是數組的大小。

使用方法時長,以獲得陣列的邏輯大小。

+0

是我想這張貼後在這裏感謝很多:) –