Swift - C API 桥接器 - 如何处理空指针 [英] Swift - C API bridge - how to handle null pointers

查看:99
本文介绍了Swift - C API 桥接器 - 如何处理空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,我使用 C API 返回带有字符数组的结构(包含 UTF8 空终止字符串或空值).

In Swift I am using C API that returns struct with char array (containing UTF8 null terminated string or null).

struct TextStruct {
   char * text;
   //other data
}

我使用:

let text: String = String(cString: data.text)

这有效,但是,当 data.textnullptr 时,这会因

This works, however, when data.text is nullptr, this fails with

fatal error: unexpectedly found nil while unwrapping an Optional value

是否有任何解决方法,或者我必须在使用 cString ctor 之前手动检查 data.text?

Is there any workaround, or I have to check data.text manually before using cString ctor?

推荐答案

除了 Gwendal Roué 的解决方案:您可以注释 C API 以指示指针是否可以为空.例如,

In addition to Gwendal Roué's solution: You can annotate the C API to indicate whether the pointer can be null or not. For example,

struct TextStruct {
    char * _Nullable text;
    //other data
};

导入到 Swift 中

is imported to Swift as

public struct TextStruct {
    public var text: UnsafeMutablePointer<Int8>?
    // ...
}

其中 var text 是一个强"可选而不是隐式解包可选.那么

where var text is a "strong" optional instead of an implicitly unwrapped optional. Then

let text = String(cString: data.text)
// value of optional type 'UnsafeMutablePointer<Int8>?' not unwrapped; ...

不再编译,并强制您使用可选绑定或其他解包技术,以及致命错误:意外发现为零"不会再发生意外了.

no longer compiles, and forces you to use optional binding or other unwrapping techniques, and the "fatal error: unexpectedly found nil" cannot happen anymore accidentally.

有关详细信息,请参阅可空性和 Objective-C"来自 Swift 博客 –尽管标题如此,但它也可以与纯 C 一起使用.

For more information, see "Nullability and Objective-C" from the Swift Blog – despite the title, it can be used with pure C as well.

这篇关于Swift - C API 桥接器 - 如何处理空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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