繁体   English   中英

如何在C#中将void指针转换为struct

[英]How I can convert void pointer to struct in C#

我有一个由第三方系统调用的dll(C#)。

该系统调用fnSys函数,并以void指针作为参数传递。 现在,我需要将此void *强制转换为我的结构。

我的代码是:

    public struct Menu
    {
        public string str1;
        public string str2;
    }

    public static unsafe int fnSys(void* value)
    {
        if (value!=null)
        {
            System.Windows.Forms.MessageBox.Show("msg");
        }

        return 1;
    }

现在,当第三方系统调用此函数时,将出现消息框,但我不知道如何将该值转换为MenuItem。 我也这样尝试过:

Menu menu = (Menu)Marshal.PtrToStructure(value, typeof(Menu));

但这不起作用。

有什么办法吗?

我找到了解决方案:

[StructLayout(LayoutKind.Sequential, Pack = 1, Size=255, CharSet = CharSet.Ansi)]
public struct Menu
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
    public string str1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
    public string str2;
}

public static unsafe int fnSys(Menu value)
{
    if (value!=null)
    {
        System.Windows.Forms.MessageBox.Show("msg");
    }

    return 1;
}

StructLayout属性使我们可以控制内存中的数据字段。

通过此链接获取更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM