2013-03-25 28 views
4

予保留的存儲器10個的項目128個字節如何非託管存儲器的陣列複製到相同的非託管內存

IntPtr dst = Marshal.AllocHGlobal (10 * 128); 

IntPtr src1 = Marshal.AllocHGlobal (128); 
// .... init scr1 from DLL 
IntPtr src2 = Marshal.AllocHGlobal (128); 
// .... init scr2 from DLL 

我需要的src1src2 128個字節元素指定的偏移量複製到dst

Marshal.Copy不適合這樣的目的。 由於srcdst處於非託管內存區域。

+0

memcopy怎麼樣? – AgentFire 2013-03-25 08:12:05

回答

5

該窗口的API函數memcopy應該做的伎倆。

[DllImport("msvcrt.dll", EntryPoint = "memcpy", 
    CallingConvention = CallingConvention.Cdecl, 
    SetLastError = false)] 
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count); 

此外,檢查了這一點:

https://stackoverflow.com/a/2658394/558018

因爲它聲稱,你可以使用unsafe上下文手動轉移所需的字節。

+0

這裏沒有內置的c#方法嗎? – Mixer 2013-03-25 08:27:54

+0

@Mixer如果你的意思是「元帥」班,那麼沒有。由於這個班是唯一的非管理員工,因此再不行。 – AgentFire 2013-03-25 08:33:47

+0

我儘量減少使用特定的Windows DLL。 這損害了可移植性。 如何指定偏移量? IntPtr無指針算術 – Mixer 2013-03-25 08:44:11

2

如果您想使用Windows API執行此操作,請使用MoveMemory

[DllImport("Kernel32.dll", EntryPoint="RtlMoveMemory", SetLastError=false)] 
static extern void MoveMemory(IntPtr dest, IntPtr src, int size);