简体   繁体   中英

How I can convert void pointer to struct in C#

I have a dll(C#) called by third-party system.

This system call fnSys function and pass as void pointer as parameter. Now I need to cast this void* to my structure.

My code is:

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

Now when third-party system call this function Message box appears, but I can't figure out how can I convert this value to MenuItem. Also I tried like this:

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

but this is not working.

Is there any ways?

I have found solution:

[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 attribute let us to control data fields in memory.

More detail by this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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