Obtain a pointer to a C char array in Swift

后端 未结 3 961
故里飘歌
故里飘歌 2021-01-06 00:19

A have a structure like this (defined in bson.h of mongodb c driver):

typedef struct
{
  uint32_t domain;
  uint32_t code;
  char message[504];
} bson_error_         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 01:09

    Quick hack to retrieve message String from bson_error_t:

    extension bson_error_t {
        mutating func messageString() -> String? {
            return String.fromCString(
                { (p:UnsafePointer) in UnsafePointer(p) }(&self.message.0)
            )
        }
    }
    
    // Usage:
    var err: UnsafeMutablePointer = ...
    ...
    let errMessage = err.memory.messageString()
    

提交回复
热议问题