Pepelee
Pepelee

Reputation: 453

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));

Upvotes: 2

Views: 645

Answers (2)

Pepelee
Pepelee

Reputation: 453

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));

Upvotes: 1

Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

No, because memory address is meaningless when GC can move objects and pointers becomes invalid. This is why a keyword reference is used here instead of pointer

Upvotes: 1

Related Questions