【问题标题】:PInvoke error marshaling C++ dll into C#, passing struct into methodPInvoke 错误将 C++ dll 编组为 C#,将结构传递给方法
【发布时间】:2018-09-23 16:21:34
【问题描述】:

大家好,我正在尝试将 C++ 项目编译成 DLL,然后使用 C# 中的结构和方法。我做了一个openCV程序,我需要来回传递数据。现在我正在尝试简单的事情来熟悉这门语言,因为这是我第一次接触 C++ 和 C# ...

所以在 C++ 中我有:

#pragma pack(push, 2)  
typedef struct 
{
//char *plate;
unsigned int width;
unsigned int height;
//bool hasPlateOn;
//unsigned char *imgData;
} Sframe;
extern "C" Sframe MYCVAPI findPossiblePlates(Sframe& in)

我尝试像这样在 C# 中使用它:

 [StructLayout(LayoutKind.Sequential)]
    struct Sframe
    {
       // [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
       // char[] plate;
        [MarshalAs(UnmanagedType.U4)]
        int width;
        [MarshalAs(UnmanagedType.U4)]
        int height;
       // bool hasPlateOn;
      //  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
      //  char[] imgData;
    }

  [DllImport(@"ALPR_pwv.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "findPossiblePlates")]
    static extern Sframe findPossiblePlates(Sframe infoOut);

但无论我尝试什么,我都会收到错误,即方法的类型签名与 PInvoke 不兼容。

有没有人可以帮助我理解这个问题?

甚至可以在 C++ 和 C# 之间传递和获取自定义结构吗?

因为最终结构最终会复杂得多,因为我必须传递带有坐标等数据的图像...

【问题讨论】:

  • UnmanagedType.ByValArray!?我在该结构中看不到任何数组。试试UnmanagedType.U4(或UnmanagedType.U2,具体取决于架构)。
  • 是的,对不起,我粘贴了错误的尝试。我也尝试了 U1 到 U8,但我一直得到同样的错误
  • 我对其进行了编辑以显示 U4 以供将来查看...@SaniSinghHuttunen
  • 删除SizeConst = 3
  • static extern Sframe findPossiblePlates(ref Sframe infoOut);

标签: c# c++ struct marshalling unmarshalling


【解决方案1】:

正如@SaniSinghHuttunen 所说,我错过了 ref 关键字,不得不使用 MarshalAs.U4 ...再次感谢 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多