【问题标题】:how to read bool from unmanaged memory, using Marshal class?如何使用 Marshal 类从非托管内存中读取布尔值?
【发布时间】:2013-10-12 05:15:04
【问题描述】:

Marshal class 不包含ReadBool 方法。如果我的 c++ 结构包含 bool 字段,那么我应该如何阅读它?我试过这样做:(bool) Marshal.ReadInt32(intPointer, offset) 但不允许将 int32 转换为 bool。

【问题讨论】:

    标签: c# interop marshalling


    【解决方案1】:

    sizeof(bool) 在 C++ is implementation-defined 中,因此最好将结构中的字段定义为已知大小的整数(例如,int32_tBOOL)。那么习惯上用0表示false而不是-0表示true

    // C++
    intPointer->int32_t_field = bool_value ? 1 : 0;
    
    // C#
    bool result = Marshal.ReadInt32(intPointer, offset) != 0;
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2016-07-15
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      相关资源
      最近更新 更多