Search code examples
c#pointersunsafe

c# creating object in specific memory address


Is it possible in C# (in a unsafe Codecontext ) to create an Object at a specific memory address?

My Code:

object _apiId = new ApiId();
var apiID = (ApiId)_apiId;
ApiId* pointer = &apiID;
Debug.Write(new Intptr(pointer));

Solution

  • Workaround:

    p/invoke the method: memcpy from msvrct.dll:

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

    you need the size of your object you want to copy:

    var size = (uint) Marshal.SizeOf(obj);
    

    you need to pin it:

    GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
    

    finally call the method memcpy:

     var _adress = NativeMethods.memcpy(new IntPtr(1115911111), handle.AddrOfPinnedObject(), new UIntPtr(size));