Pinvoke Bool - MarshalDirectiveExeption

Pinvoke Bool - MarshalDirectiveExeption

本文关键字:MarshalDirectiveExeption Bool Pinvoke      更新时间:2023-10-16

我想从非托管代码中返回一个带有 bool 属性的结构:

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 不兼容。

如果存在此异常的处理程序,则可以安全地继续该程序。

正如错误所说,该结构不兼容 p/invoke。函数返回值必须是可 blited的,而该类型不是。信息可以在这里找到:http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx

从平台调用调用返回的结构必须是可 blitt 类型。平台调用不支持将不可 blit 结构作为返回类型。

同一主题继续列出可 blitit 的类型,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

相关文章:
  • 没有找到相关文章