转换一个C字符数组为String [英] Converting a C char array to a String

查看:106
本文介绍了转换一个C字符数组为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个雨燕的程序,做互操作与C库。这个C库里面返回一个的char [] 数组的结构,像这样的:

I have a Swift program that does interop with a C library. This C library returns a structure with a char[] array inside, like this:

struct record
{
    char name[8];
};

这个定义是正确导入到斯威夫特。然而,该领域是PTED为8的的元组 INT8 元素(输入(INT8,INT8间$ P $, INT8,INT8,INT8,INT8,INT8,INT8)),我不知道如何变换成字符串与斯威夫特。

The definition is correctly imported into Swift. However, the field is interpreted as a tuple of 8 Int8 elements (typed (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)), which I have no idea how to transform into a String with Swift.

有没有接受一个 INT8 元组字符串初始化,并且它似乎并不可能得到一个指针元组的第一个元素(因为类型可以是异质的,这并不令人惊讶)。

There is no String initializer that accepts an Int8 tuple, and it doesn't seem possible to get a pointer to the first element of the tuple (since types can be heterogenous, that's not really surprising).

现在,我的最好的想法是创建一个接受一个指向结构本身并返回一个微小的C函数名称的char * 指针,而不是一个数组,并与该走了。

Right now, my best idea is to create a tiny C function that accepts a pointer to the structure itself and return name as a char* pointer instead of an array, and go with that.

是存在的,但是,是纯粹的斯威夫特办法做到这一点?

Is there, however, are pure Swift way to do it?

推荐答案

您可以得到一个指针元组

You can get a pointer to the tuple with

withUnsafePointer(&record.name) { ... }

(这需要记录是一个的变量的)。然后该指针可以转换
UnsafePointer< INT8> String.fromCString使用()

(this requires record to be a variable). The pointer can then be converted to anUnsafePointer<Int8> and used in String.fromCString():

var record = someFunctionReturningAStructRecord()

let name = withUnsafePointer(&record.name) {
    String.fromCString(UnsafePointer($0))!
}

这个假设中的字节名称[] 是一个有效的NULL结尾的UTF-8序列。

This assumes that the bytes in name[] are a valid NUL-terminated UTF-8 sequence.

这篇关于转换一个C字符数组为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆