[英]How I can convert void pointer to struct in C#
I have a dll(C#) called by third-party system. 我有一个由第三方系统调用的dll(C#)。
This system call fnSys function and pass as void pointer as parameter. 该系统调用fnSys函数,并以void指针作为参数传递。 Now I need to cast this void* to my structure.
现在,我需要将此void *强制转换为我的结构。
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. 现在,当第三方系统调用此函数时,将出现消息框,但我不知道如何将该值转换为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. StructLayout属性使我们可以控制内存中的数据字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.