c#在特定的内存地址中创建对象

问题描述 投票:2回答:2

是否有可能在C#(在一个不安全的Codecontext中)在特定的内存地址创建一个对象?

我的代码:

object _apiId = new ApiId();
var apiID = (ApiId)_apiId;
ApiId* pointer = &apiID;
Debug.Write(new Intptr(pointer));
c# pointers unsafe
2个回答
1
投票

不,因为当GC可以移动对象并且指针变得无效时,内存地址是没有意义的。这就是为什么在这里使用关键字reference而不是pointer


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));
© www.soinside.com 2019 - 2024. All rights reserved.