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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9175861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:15:48  来源:igfitidea点击:

How can I convert an unmanaged IntPtr type to a c# string?

c#unmanaged

提问by Benj

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:

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

[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);
    }

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.

我想知道的是如何获取 IntPtr 类型的 lParam 对象的字符串表示。它本质上是 C++ 领域中的 void*,我可以以某种方式将它投射到 C# 中吗?据推测,这样做本质上是不安全的。

采纳答案by GSerg

Marshal.PtrToStringAutoMethod (IntPtr)

Marshal.PtrToStringAuto方法 (IntPtr)

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

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

回答by Ilia Koulikov

The above answer was great and it nearly solved the same issue for me but... I got what looks like Chinese characters back from the method (潆湵?瑡氠慥瑳漠敮爠灥慥整?浩条?慮敭???). What I had to do was use the Marshal.PtrToStringAnsi(IntPtr) method as described here: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.ptrtostringansi.aspxand here: http://answers.unity3d.com/questions/555441/unitys-simplest-plugin-print-does-not-work.html.

上面的答案很好,它几乎为我解决了同样的问题,但是......我从方法(潆湵?瑡氠慥瑳漠敮爠整灥慥?浩条?敭? ??)。我必须做的是使用 Marshal.PtrToStringAnsi(IntPtr) 方法,如下所述 :http: //msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.ptrtostringansi.aspx和这里: http ://answers.unity3d.com/questions/555441/unitys-simplest-plugin-print-does-not-work.html

Once I made the change, my String was in English once more. Not sure why that was happening, but there ya go!

一旦我做出改变,我的字符串又是英文的。不知道为什么会这样,但是你去吧!