示例工程 25-c-interop
25-c-interop/Sources/Ch25Kit/CInterop.swift
import Ch25C
/// 给 C 结构体一个 Swift 侧别名,调用方不必再导入 C 模块。
public typealias CPoint = Point2C
/// C 结构体在 Swift 里是普通值类型:字段可见、可以直接构造。
public enum CInterop {
public static func add(_ lhs: Int32, _ rhs: Int32) -> Int32 {
c_add(lhs, rhs)
}
/// Swift `String` 必须显式转成 C 字符串,`withCString` 保证生命周期覆盖调用。
public static func byteLength(_ text: String) -> Int {
text.withCString { pointer in
c_strlen(pointer)
}
}
/// 用可变缓冲区把 C 写入的内存带回 Swift。
public static func filled(count: Int, value: Int32) -> [Int32] {
var buffer = [Int32](repeating: 0, count: count)
buffer.withUnsafeMutableBufferPointer { pointer in
c_fill(pointer.baseAddress, pointer.count, value)
}
return buffer
}
public static func makePoint(x: Int32, y: Int32) -> CPoint {
c_make_point(x, y)
}
public static func sum(_ point: CPoint) -> Int32 {
c_sum_point(point)
}
/// `@convention(c)` 闭包可以传给 C 函数指针参数。
public static func callDouble(_ value: Int32) -> Int32 {
let callback: @convention(c) (Int32) -> Int32 = { $0 * 2 }
return c_call_callback(callback, value)
}
}
/// 导出给 C 调用的 Swift 函数;参数与返回值必须是 C 兼容类型。
@_cdecl("swift_triple")
public func swiftTriple(_ value: Int32) -> Int32 {
value * 3
}
public enum ExportedFunction {
public static func callTriple(_ value: Int32) -> Int32 {
swiftTriple(value)
}
}