在 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 字符数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)