Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a array of unmanaged memory into the same unmanaged memory

I reserved memory 10 items of 128 bytes

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

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

I need to copy the 128 bytes elements of src1 and src2 to dst at the specified offset.

Marshal.Copy not suitable for such purposes. Since the src and dst in unmanaged memory area.

like image 958
Mixer Avatar asked Feb 18 '23 01:02

Mixer


1 Answers

The Window's API function memcopy should do the trick.

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

Also, check this out:

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

As it claims, you can use unsafe context to manually transfer necessary bytes.

like image 151
AgentFire Avatar answered Apr 09 '23 20:04

AgentFire