【问题标题】:heap corruption when using pin_ptr to copy from native code to managed code使用 pin_ptr 从本机代码复制到托管代码时堆损坏
【发布时间】:2018-06-21 22:52:53
【问题描述】:

我正在尝试将 unsigned short 从本机代码复制到托管代码,但在调用 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;
....

【问题讨论】:

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


    【解决方案1】:
    int frSize = 300;
    input = new uns16(frSize);
    

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

    input = new uns16[frSize];
    

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 2014-05-04
      • 2023-04-01
      • 2011-11-26
      • 2019-10-06
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多