[英]Is it possible to reinterpret an object reference as native int using c# code?
Disclaimer: I understand this is an unsafe operation and bad practice, I merely want to know if it's possible.免责声明:我知道这是一种不安全的操作和不好的做法,我只是想知道它是否可能。
Basically, I'm trying to convert an object reference to a nint
( IntPtr
).基本上,我正在尝试将 object 引用转换为
nint
( IntPtr
)。 They take up the same size in memory, so it should be possible in theory.它们在memory中占据相同的大小,所以理论上应该是可以的。 I've gotten it to work using a DynamicMethod:
我已经使用 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);
Is this possible using only C# code?这是否可能仅使用 C# 代码? I haven't found anything suitable in
System.Runtime.CompilerServices.Unsafe
.我没有在
System.Runtime.CompilerServices.Unsafe
找到任何合适的东西。
I've also tried this:我也试过这个:
[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;
But I get the following error:但我收到以下错误:
System.TypeLoadException: 'Could not load type 'Cast' from assembly because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.'
System.TypeLoadException:'无法从程序集中加载类型'Cast',因为它包含偏移量 0 处的 object 字段,该字段未正确对齐或被非对象字段重叠。
I haven't found anything suitable in
System.Runtime.CompilerServices.Unsafe
我在
System.Runtime.CompilerServices.Unsafe
中没有找到任何合适的东西
object obj = new object();
nint asNativeInt = Unsafe.As<object, nint>(ref obj);
There you have it.你有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.