Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在C中将void指针转换为struct#_C#_C++_Marshalling_Unmanaged_Unsafe - Fatal编程技术网

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

C# 如何在C中将void指针转换为struct#,c#,c++,marshalling,unmanaged,unsafe,C#,C++,Marshalling,Unmanaged,Unsafe,我有一个由第三方系统调用的dll(C#) 此系统调用fnSys函数,并将其作为无效指针作为参数传递。 现在,我需要把这个空虚抛到我的结构上 我的代码是: public struct Menu { public string str1; public string str2; } public static unsafe int fnSys(void* value) { if (value!=null)

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

此系统调用fnSys函数,并将其作为无效指针作为参数传递。 现在,我需要把这个空虚抛到我的结构上

我的代码是:

    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属性允许我们控制内存中的数据字段

通过此

我找到了解决方案:

[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属性允许我们控制内存中的数据字段


更详细地说,“不工作”是毫无意义的。这怎么会失败呢?哦,发布调用者使用的C结构。它不应该是
Menu Menu=(Menu)value?“不工作”没有意义。这怎么会失败呢?哦,发布调用者使用的C结构。它不应该是
Menu Menu=(Menu)value