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



我正在尝试将无符号短代码从本机代码复制到托管代码,但是调用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;
....
int frSize = 300;
input = new uns16(frSize);

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

input = new uns16[frSize];

最新更新