如何将非托管IntPtr类型转换为C#字符串? [英] How can I convert an unmanaged IntPtr type to a c# string?

查看:458
本文介绍了如何将非托管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.

这篇关于如何将非托管IntPtr类型转换为C#字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆