我需要从 C DLL 获取数据到 C# 应用程序。这是错误:
无法编组类型为“KnittingWago.Common.WAGO_DATA_TO_USER_T”的字段“计数器”:托管/非托管类型组合无效(数组字段必须与 ByValArray 或 SafeArray 配对)。
这是DLL .h
#define WAGO_NB_COUNTERS_C 80
#define WAGO_NB_ENCODERS_C 10
struct WAGO_DATA_TO_USER_T
{
unsigned int Counters[WAGO_NB_COUNTERS_C];
int Encoders[WAGO_NB_ENCODERS_C];
unsigned int Weight;
bool CalibrationValid;
bool LastCalibrationFailed;
};
这是 C# 结构声明:
const int WAGO_NB_COUNTERS_C = 80;
const int WAGO_NB_ENCODERS_C = 10;
struct WAGO_DATA_TO_USER_T
{
[MarshalAs(UnmanagedType.U4, SizeConst = GlobalConstant.WAGO_NB_COUNTERS_C)]
UInt32[] Counters;
[MarshalAs(UnmanagedType.I4, SizeConst = GlobalConstant.WAGO_NB_ENCODERS_C)]
Int32[] Encoders;
UInt32 Weight;
Boolean CalibrationValid;
Boolean LastCalibrationFailed;
};
如何声明 C# 结构以获取正确的数据而不会出错?
谢谢
编辑 :
我已将 Struct 重写为:
internal struct WAGO_DATA_TO_USER_T
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GlobalConstant.WAGO_NB_COUNTERS_C)]
UInt32[] Counters;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GlobalConstant.WAGO_NB_ENCODERS_C)]
Int32[] Encoders;
UInt32 Weight;
Boolean CalibrationValid;
Boolean LastCalibrationFailed;
};
不再有错误,但值与预期不符。
应该像:
Counter[0] = ~ 5000
Counter[1] = ~ 30000
Counter[2-79] = 0
真的是:
Counter[0] = 40
Counter[1] = 1080228
Counter[2] = 82964616
Counter[3-79] = All have a non-zero value