【问题标题】:Is it possible to reinterpret an object reference as native int using c# code?是否可以使用 c# 代码将对象引用重新解释为本机 int?
【发布时间】:2022-08-02 20:08:30
【问题描述】:

免责声明:我理解这是一种不安全的操作和不好的做法,我只是想知道它是否可能。

基本上,我试图将对象引用转换为nint (IntPtr)。它们在内存中占用相同的大小,因此理论上应该是可能的。我已经使用 DynamicMethod 让它工作:

DynamicMethod dyn = new DynamicMethod(\"\", typeof(nint), new[] { typeof(object) });
ILGenerator il = dyn.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
Func<object, nint> objectToIntFunction = (Func<object, nint>)dyn.CreateDelegate(typeof(Func<object, nint>));
object obj = new object();
nint asNativeInt = objectToIntFunction(obj);

这是否可能仅使用 C# 代码?我在System.Runtime.CompilerServices.Unsafe 中没有找到任何合适的东西。

我也试过这个:

[StructLayout(LayoutKind.Explicit)]
struct Cast
{
    [FieldOffset(0)]
    public nint Number;
    [FieldOffset(0)]
    public object Object;
};

Cast cast = new Cast
{
    Object = obj
};
nint number = cast.Number;

但我收到以下错误:

System.TypeLoadException:\'无法加载类型 \'Cast\' 从程序集中,因为它 包含偏移量 0 的对象字段,该对象字段未正确对齐或 被非对象字段重叠。\'

  • 这不仅仅是一个不好的做法。它没有用,因为 GC 可以在任何时间点将对象移动到新位置。只有获得指向具有固定位置的东西的指针才是明智的,因为它既不是也不能被固定。

标签: c# unsafe reinterpret-cast


【解决方案1】:

我在System.Runtime.CompilerServices.Unsafe 中没有找到合适的东西

object obj = new object();
nint asNativeInt = Unsafe.As<object, nint>(ref obj);

你有它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多