使用pin_ptr从本机代码复制到托管代码时发生堆损坏

时间:2018-06-21 22:52:54

标签: c++-cli memcpy managed heap-corruption

我试图将无符号的短代码从本机代码复制到托管代码,但是在调用memcpy时出现堆损坏。

INPUT: unsigned short* input
OUTPUT: array<unsigned short> output

我有以下代码,如果我将testDataSize设置为100,则看不到损坏。 有人可以帮忙一下吗?

谢谢

typedef unsigned short uns16;

// DLL Entry Point
void main()
{
    int testDataSize = 600;
    int frSize = testDataSize / 2;


    for (int j = 0; j < 1; j++) 
    {
        uns16* input;
        array<uns16>^ output1;
        array<uns16>^ output2;

        input = new uns16(frSize);
        output1 = gcnew array <uns16>(frSize);
        output2 = gcnew array <uns16>(frSize);

        // initialize
        for (int i = 0; i < frSize; i++)
        {
            input[i] = i;
        }

        //test 1
        Stopwatch^ sw1 = Stopwatch::StartNew();
        //-------------------------------------------------------------------
        array<short>^ frameDataSigned = gcnew array<short>(frSize);
        Marshal::Copy(IntPtr((void*)(input)), frameDataSigned, 0, frameDataSigned->Length);
        System::Buffer::BlockCopy(frameDataSigned, 0, output1, 0, (Int32)(frSize) * 2);
        //-------------------------------------------------------------------
        auto res1 = sw1->ElapsedTicks;

        //test 2
        Stopwatch^ sw2 = Stopwatch::StartNew();
        //-------------------------------------------------------------------
        cli::pin_ptr<uns16> pinnedManagedData = &output2[0];
        memcpy(pinnedManagedData, (void*)(input), frSize * sizeof(uns16));
        //-------------------------------------------------------------------
        auto res2 = sw2->ElapsedTicks;
....

1 个答案:

答案 0 :(得分:2)

int frSize = 300;
input = new uns16(frSize);

这不会分配数组。它分配一个uint16_t,并将其值设置为300。您需要使用方括号分配数组。

input = new uns16[frSize];