【发布时间】: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