相关疑难解决方法(0)

如何获取指向托管类的原始内存指针?

如何在 C# 中找到指向托管类的原始指针,并且希望它是内存中的原始大小?显然,这是 CLR 不允许的——更准确地说,是严格禁止的,因为出于稳定性和安全的原因,永远不应该使用托管类的非托管表示形式——所以我正在寻找一个黑客。我不是在寻找序列化 - 我实际上需要一个托管类的转储,因为它在原始内存中表示。

更准确地说,我正在getObjectPtr以下示例中寻找类似函数的东西:

IntPtr getObjectPtr(Object managedClass) {...}

void main() {
    var test=new TestClass();
    IntPtr* ptr_to_test=getObjectPtr(test);
    Console.WriteLine(ptr_to_test.ToString());
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

编辑: 我终于自己找到了一个解决方案,当我回来将其作为答案发布时,对如此快速发布的答案数量感到非常惊讶......谢谢大家!这非常快,而且完全出乎意料。

最接近我的解决方案是@thehennyy 的解决方案,但我没有发布它,因为@Chino 提出了更好的解决方案(对不起,我一开始误认为它是错误的,我只是忘记再次取消引用指针)。它不需要不安全的代码,并且更能容忍 GC:

class Program
{
    // Here is the function in case anyone needs it.
    // Note, though, it does not preserve the handle while you work with
    // pointer, so it is less reliable than the code in Main():
    static IntPtr getPointerToObject(Object unmanagedObject)
    {
        GCHandle gcHandle = GCHandle.Alloc(unmanagedObject, …
Run Code Online (Sandbox Code Playgroud)

c# reflection pointers

5
推荐指数
2
解决办法
2539
查看次数

标签 统计

c# ×1

pointers ×1

reflection ×1