C typedef

时间:2015-06-30 17:16:35

标签: swift

我需要使用第三方C库,其源代码我无法修改,并且大量使用隐式类型转换和typedef来设置其结构的值。它们都是下面的内容,这是与此库交互的首选方式。我以前在Objective C代码中使用它没有问题,所以现在我主要移植一些旧的代码,但感觉就像我经常用Swift打砖墙。

tl; dr:如何在Swift中为C结构成员分配不同的typedef值,同时自动处理类型转换(所有typedef都是下面的int)?

例如,请考虑以下定义:

struct library_struct {
    int member;
};        

typedef enum library_consts {
    LIBRARY_DEFINED_VALUE = 0
} library_consts;

在C或Objective C中,执行以下操作绝对可以接受:

library_struct a;
a.member = LIBRARY_DEFINED_VALUE

然而,试图在Swift中做同样的事情

var a: library_struct = library_struct()
a.member = LIBRARY_DEFINED_VALUE

导致错误: Cannot assign a value of type 'library_consts' to a value of type 'Int32'

我尝试了几种方法:

  1. 使用Int32()投射。这会导致Cannot find an initializer for type 'Int32' that accepts and argument list of type (library_consts)错误。

  2. 使用LIBRARY_DEFINED_VALUE.rawValue。这不会起作用,因为rawValue将返回一个UInt32,因此我将收到以下错误:Cannot assign a value of type 'UInt32' to a value of type 'Int32'

  3. 唯一的选择是将rawValue返回的值再次投射到Int32,如下所示:Int32(LIBRARY_DEFINED_VALUE.rawValue)

  4. 这样可行,但是进行双重转换感觉不对,它并不能解决更复杂的情况,例如将一个不同类型的值(但仍然是一个int)分配给结构成员,如下所示:

    enum library_consts
    {
        LIB_FALSE=0,
        LIB_TRUE=1
    };
    
    typedef int lib_bool_t;
    
    typedef struct another_struct {
        lib_bool_t aFlag;
    }
    
    var b: another_struct = another_struct()
    a.aFlag = LIB_FALSE
    

    这将导致错误输出"无法指定类型' library_consts'的值类型为' lib_bool_t'"

1 个答案:

答案 0 :(得分:1)

如果你不能改变,我担心没有更容易的解决办法 C界面。使用"生成的界面"在Xcode 7中查看即可 看到了

enum library_consts
{
    LIB_FALSE=0,
    LIB_TRUE=1
};

typedef int lib_bool_t;

映射到Swift为

struct library_consts : RawRepresentable {
    init(_ rawValue: UInt32)
    init(rawValue: UInt32)
    var rawValue: UInt32
}

typealias lib_bool_t = Int32

(Swift中的C int类型为Int32

Swift没有隐式类型转换,这意味着你有 明确转换类型。在第二种情况下,它将是

var b: another_struct = another_struct()
b.aFlag = lib_bool_t(LIB_FALSE.rawValue)
相关问题