2

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));
1
  • The Marshall.StructureToPtr method may help you. If you explain a little better what you want to achieve I could give you a better hint. Commented Dec 4, 2014 at 14:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Personally, I don't find the explanation satisfatory. In other situations, GC can be "taken out of the equation" (e.g., GCHandleType.Pinned), so it wouldn't surprise me if something similar could be done in this situation.
Arrays and so on can be pinned, but you haven't full C++ control over unsafe code. For example, code like MyStruct x = *(MyStruct*)((void*)0xDEADBEEF) are not allowed even in unsafe C#
I know, "unsafe" is limited in C#, but I don't think "memory address is meaningless when GC can move objects and pointers becomes invalid" is the reason why.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.