在C#(在不安全的Codecontext中)是否可以在特定的内存地址创建一个Object?
我的代码:
object _apiId = new ApiId();
var apiID = (ApiId)_apiId;
ApiId* pointer = &apiID;
Debug.Write(new Intptr(pointer));
答案 0 :(得分:1)
不,因为当GC可以移动对象并且指针变得无效时,内存地址没有意义。这就是此处使用关键字reference
而非pointer
答案 1 :(得分:1)
解决方法:
p /调用方法:来自msvrct.dll的memcpy:
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl,
SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);
您需要要复制的对象的大小:
var size = (uint) Marshal.SizeOf(obj);
你需要钉住它:
GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
最后调用方法memcpy:
var _adress = NativeMethods.memcpy(new IntPtr(1115911111), handle.AddrOfPinnedObject(), new UIntPtr(size));