如何将非托管IntPtr类型转换为C#字符串?

如何将非托管IntPtr类型转换为C#字符串?

问题描述:

我是C#的新手(来自C ++的本机背景),我试图编写一个小的UI来打印Windows广播消息等。我已经在C#程序中覆盖了默认的WndProc消息循环,如下所示:

I'm new to C# (from a native C++ background) and I'm trying to write a little UI to print windows broadcast messages among other things. I've overridden the default WndProc message loop in my C# program like so:

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override void WndProc(ref Message m)
    {
        // Listen for operating system broadcasts.
        switch (m.Msg)
        {
            case WM_SETTINGCHANGE:

                this.richTextLog.Text += "WM_SETTINGCHANGE - lParam=" + m.LParam.ToString() + "\n";

                break;
        }
        base.WndProc(ref m);
    }

我想知道的是如何获取...的字符串表示形式类型为IntPtr的lParam对象。它在C ++领域本质上是一个void *,我可以以某种方式将其强制转换为C#吗?大概这样做本质上是不安全的。

What I'd like to know, is how to obtain a string representation of the lParam object which is of type IntPtr. It's essentially a void* in C++ land, can I cast it inside C# somehow? Presumably doing so is inherently unsafe.

Marshal.PtrToStringAuto 方法(IntPtr)

Marshal.PtrToStringAuto Method (IntPtr)

分配托管的 String 并将所有字符复制到非托管内存中存储的字符串中的第一个空字符为止。

Allocates a managed String and copies all characters up to the first null character from a string stored in unmanaged memory into it.