【发布时间】:2013-10-12 05:15:04
【问题描述】:
Marshal class 不包含ReadBool 方法。如果我的 c++ 结构包含 bool 字段,那么我应该如何阅读它?我试过这样做:(bool) Marshal.ReadInt32(intPointer, offset) 但不允许将 int32 转换为 bool。
【问题讨论】:
标签: c# interop marshalling
Marshal class 不包含ReadBool 方法。如果我的 c++ 结构包含 bool 字段,那么我应该如何阅读它?我试过这样做:(bool) Marshal.ReadInt32(intPointer, offset) 但不允许将 int32 转换为 bool。
【问题讨论】:
标签: c# interop marshalling
sizeof(bool) 在 C++ is implementation-defined 中,因此最好将结构中的字段定义为已知大小的整数(例如,int32_t 或 BOOL)。那么习惯上用0表示false而不是-0表示true:
// C++
intPointer->int32_t_field = bool_value ? 1 : 0;
// C#
bool result = Marshal.ReadInt32(intPointer, offset) != 0;
【讨论】: