在swift中使用C结构

时间:2016-08-01 16:06:55

标签: ios swift struct

我使用的是C语言的供应商框架,这个框架有以下结构:

typedef struct tTINFO {
    int size;              

    const char* vId; 
    const char* cId; 
    const char* cmm;  
    const char* cKey;
} TINFO;

这样导入swift:

public struct tTINFO {
    /**< \brief Size of the structure */
    public var size: Int32

    /**< \brief Pointer to a null-terminated string*/
    public var vId: UnsafePointer<Int8>
    /**< \brief Pointer to a null-terminated string*/
    public var cId: UnsafePointer<Int8>
    /**< \brief Pointer to a null-terminated string. May be NULL. */
    public var cmm: UnsafePointer<Int8>
    public var cKey: UnsafePointer<Int8>
    public init()
    public init(size: Int32, vId: UnsafePointer<Int8>, cId: UnsafePointer<Int8>, cmm: UnsafePointer<Int8>, cKey: UnsafePointer<Int8>)
}
public typealias TINFO = tTINFO

我试图在swift中使用:

var cI:TINFO = TINFO(size: sizeof(TINFO),
                     vId: "vID",
                     cId: "cID",
                     cmm: nil,
                     cKey: "cKey")

并将其传递给标题

中的以下函数
public func TI(CI: UnsafeMutablePointer<TINFO>, _ Reserved: UnsafeMutablePointer<Void>, _ Flags: Int32) -> TT

因此:

TI(&cI, nil, initOptions)

现在编译器没有给我的代码错误,它在运行时都没有崩溃,但是,在swift中使用这段代码时的框架会给我一个错误。

我的问题是:

  • 我的结构初始化是否正确,我真的认为这是错误的,因为我不能再打印cI的内容我只得到指针值?如果有问题我怎么纠正呢?

  • 我在几个地方看到,要获得结构的大小我应该使用sizeof(TInfo)其他人说因为填充它的步幅但是当它们应用时我仍然不清楚它们都返回相同的大小。

将不胜感激任何帮助。顺便说一句,我正在使用swift2.3

编辑:

感谢@AMomchilov在此post设置中共享的链接在将结构传递到结构之前,每个结构属性都是CChar,例如:

("vID" as NSString).UTF8String

1 个答案:

答案 0 :(得分:0)

您需要致电utf8String以获取必要的UnsafePointer<Int8>,null-termianted字符串:

import Foundation
var cI:TINFO = TINFO(size: sizeof(TINFO),
                     vId: "vID".utf8String,
                     cId: "cID".utf8String,
                     cmm: nil,
                     cKey: "cKey".utf8String)