我想从带有bool属性的非托管代码中返回一个struct:
EXTERN_C UA_EXPORT_WRAPPER_IMPORT DN_OPstruct DOTNET_GetOperation(){
DN_OPstruct op;
op.direction = true;
return op; }
struct DN_OPstruct{
bool direction; }我的C#代码看起来如下:
[StructLayout(LayoutKind.Sequential,Pack = 8, CharSet = CharSet.Ansi)]
public struct DN_OPstruct{
[MarshalAs(UnmanagedType.I1)]
bool direction; }
[DllImport("somedll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "somefct",
ExactSpelling = true, CharSet = CharSet.Ansi)]
public static extern DN_OPstruct DOTNET_GetOperation();不幸的是,我收到了以下错误消息:
'System.Runtime.InteropServices.MarshalDirectiveException‘类型的异常发生在WindowsFormsApplication1中,但未在用户代码中处理
附加信息:方法的类型签名与PInvoke不兼容。
如果存在此异常的处理程序,则可以安全地继续该程序。
发布于 2014-11-24 14:08:51
正如错误所述,结构与p/invoke不兼容。函数返回值必须是可闪存的,而该类型不是。这些信息可以在这里找到:http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx
从平台调用返回的结构必须是闪存类型。平台调用不支持非闪存结构作为返回类型。
这个主题将继续列出可闪存的类型,而bool不在列表中。
您应该使用byte而不是bool。你可以这样把它包起来:
[StructLayout(LayoutKind.Sequential)]
public struct DN_OPstruct
{
private byte _direction;
public bool direction
{
get { return _direction != 0; }
set { _direction = (byte)(value ? 1 : 0); }
}
}我还想指出,在这里使用Pack似乎是不正确的,没有必要在任何地方指定CharSet。
https://stackoverflow.com/questions/27105915
复制相似问题