Search code examples
c#c++marshallingunmanagedunsafe

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?


Solution

  • 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