在 Swift 中获取指向 C 字符数组的指针

Obtain a pointer to a C char array in Swift(在 Swift 中获取指向 C 字符数组的指针)

本文介绍了在 Swift 中获取指向 C 字符数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A 有这样的结构(在 mongodb c 驱动的 bson.h 中定义):

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_t;

在 Swift 中,我有一个指向这个结构的指针,如下所示:

In Swift I have a pointer to this structure like this:

err: UnsafePointer<bson_error_t> = ...

现在无论我做什么,我都无法将 message[504] (Swift 将其视为 (Int8, Int8, Int8, ...504 次) 的元组)转换为 char* 在 String.fromCString() 中使用它.甚至有可能在 Swift 中做到这一点吗?作为临时解决方案,我在一个单独的 .c 文件中创建了一个辅助 C 函数,该文件采用 err *bson_error_t 并返回 char*,但这是奇怪的是Swift 自己做不到.

Now whatever I do I cannot convert message[504] (which Swift sees as a tuple of (Int8, Int8, Int8, ...504 times)) to char* to use it in String.fromCString(). Is it even possible to do that in Swift? As a temporary solution I created a helper C function in a separate .c file which takes err *bson_error_t and returns char*, but this is weird if Swift cannot do it by itself.

推荐答案

这里是我的建议(类似于 rintaro 的方法,可能稍微简单一些):

Here my suggestion (similar to rintaro's approach, perhaps slightly simpler):

var err: UnsafeMutablePointer<bson_error_t> = ...

var msg = err.memory.message
let msgString = withUnsafePointer(&msg) { String.fromCString(UnsafePointer($0)) }
println(msgString)

这篇关于在 Swift 中获取指向 C 字符数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Swift 中获取指向 C 字符数组的指针

基础教程推荐