繁体   English   中英

Swift:访问作为对象的 C 结构成员

[英]Swift: Accessing C Struct Members That Are Objects

我现在拥有的:

在我的应用程序中,我有一个保存颜色的全局 C 结构:

//Colors.h

extern struct MYColors *appColors;

struct MYColors
{
    CGColorRef appBackgroundColor;
    // ...Lots more colors follow
};

以及匹配的实现文件:

//Colors.m

struct MYColors *appColors = calloc(1, sizeof(struct MYColors));
appColors->appBackgroundColor = CGColorCreateGenericRGB(23.0f/255.0f, 24.0f/255.0f, 26.0f/255.0f, 1.0f);

这使我可以集中所有应用程序的颜色。 在各种自定义视图中,我在 Objective-C 中编写了这样的代码:

- (void) updateLayer {
    someCGLayer.backgroundColor = appColors->appBackgroundColor;
}

我需要的:

我开始将此应用程序迁移到 Swift,但我无法弄清楚如何访问此 C Struct 的导入版本。 我看过很多关于包含intfloat等的简单结构的帖子。

如果我有这个结构体的全局实例(基本上是单例) appColors ,我如何从 Swift 访问该结构体的成员?


我认为可行的方法:

这不起作用。 Swift 声称MYColors没有appBackgroundColor

let color: CGColor = UnsafePointer<MYColors>(appColors).appBackgroundColor

我还想也许我只需要像这样访问单身人士:

let color: CGColor = UnsafePointer<MYColors>(MyModuleName.appColors!).appBackgroundColor

但这也行不通。

C 声明

extern struct MYColors * appColors;

导入到 Swift 中

public var appColors: UnsafeMutablePointer<MYColors>!

在 Swift 中通过pointee属性取消引用指针,因此 Swift 等效于 (Objective-)C 代码

appColors->appBackgroundColor

appColors.pointee.appBackgroundColor

该值的类型是Unmanaged<CGColor>! 因为 Swift 编译器不知道应该如何管理对象的内存。 在您的情况下,调用者不负责释放对象,因此最终代码是:

let bgColor = appColors.pointee.appBackgroundColor.takeUnretainedValue()

有关非托管引用的更多信息,请参阅Unmanaged

备注:如果appColors和所有 struct 成员在访问时保证为非 NULL,那么您可以在接口中使用_Nonnull注释它们:

struct MYColors {
    CGColorRef _Nonnull appBackgroundColor;
    // ...
};

extern struct MYColors * _Nonnull appColors;

Swift 编译器然后将变量作为非可选变量而不是(隐式解包的)可选变量导入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM