我正在将本机 C++ 库翻译成 C#。原始函数分配结构的一些内存,对当前进程进行一些内存操作,并将操作后的字节返回到结构内的字节缓冲区。
该结构定义如下:
typedef struct tdMEM_SCATTER_HEADER {
DWORD magic;
WORD version;
WORD Future1;
ULONG64 qwA;
DWORD cbMax;
DWORD cb;
PBYTE pb;
PVOID pvReserved1;
PVOID pvReserved2;
PVOID Future2[8];
} MEM_SCATTER_HEADER, *PMEM_SCATTER_HEADER, **PPMEM_SCATTER_HEADER;
原函数定义如下:
DWORD Scatter(_Inout_ PPMEM_SCATTER_HEADER ppMEMs, _In_ DWORD count);
并且分配顺序是
pbBuffer = LocalAlloc(0, count * (sizeof(PMEM_SCATTER_HEADER) + sizeof(MEM_SCATTER_HEADER) + 0x1000));
ZeroMemory(pbBuffer, count * (sizeof(PMEM_SCATTER_HEADER) + sizeof(MEM_SCATTER_HEADER)));
for(i = 0; i < cMEMs; i++) {
pMEM->pb = pbData + ((QWORD)i << 12); // Allocating return bytes buffer.
}
这是我尝试过的:
结构编组:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct MEM_SCATTER_HEADER
{
public uint magic;
public ushort version;
public ushort Future1;
public ulong qwA;
public uint cbMax;
public uint cb;
[MarshalAs(UnmanagedType.ByValArray)]
public byte[] pb;
public IntPtr pvReserved1;
public IntPtr pvReserved2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public IntPtr[] Future2;
}
内存分配:
MEM_SCATTER_HEADER[] header = new MEM_SCATTER_HEADER[count];
for (int i = 0; i < count; i++)
{
header[i].pb = new byte[0x1000];
Array.Clear(header[i].pb, 0, header[i].pb.Length); // Fill array with 0
}
DLL导入:
[DllImport("testC.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint Scatter(ref MEM_SCATTER_HEADER ppMems, uint count);
最后是函数调用:
uint count = Scatter(ref header, count);
我有时间调试我是否错误地编组数据,或者我是否必须进行一些手动编组以摆脱异常:“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”在函数调用。