Swift 调用 c 语言
2018-11-03 本文已影响0人
北极雪狐
无参数型 define
常量的定义
#define FADE_ANIMATION_DURATION 0.35
#define VERSION_STRING "2.2.10.0a"
#define MAX_RESOLUTION 1268
#define HALF_RESOLUTION (MAX_RESOLUTION / 2)
#define IS_HIGH_RES (MAX_RESOLUTION > 1024)
此类 define,Swift 会转换为常量定义,等同于如下代码
let FADE_ANIMATION_DURATION = 0.35
let VERSION_STRING = "2.2.10.0a"
let MAX_RESOLUTION = 1268
let HALF_RESOLUTION = 634
let IS_HIGH_RES = true
非常量的定义
#define DEBUG
#define MACOS
这类 define,Swift 不会转换
带参数型 define
Swift 不会转换带参数型的 define,并且 Apple 建议使用 函数 或 泛型 来代替些类 define
struct
struct Color {
float r, g, b;
};
typedef struct Color Color;
等同于以下定义
public struct Color {
var r: Float
var g: Float
var b: Float
init()
init(r: Float, g: Float, b: Float)
}
Unions
union SchroedingersCat {
bool isAlive;
bool isDead;
};
union 等样是转换为 struct,但使用的存储方式和 C 是一样的,也就是更改 isAlive 同样会更改 isDead
struct SchroedingersCat {
var isAlive: Bool { get set }
var isDead: Bool { get set }
init(isAlive: Bool)
init(isDead: Bool)
init()
}
Bit Fields
struct date {
int day:5;
int mouth:4;
int year: 14;
}
同样转换成 struct,但保持与 C 一致的存储方式
struct date {
var day: Int { get set }
var month: Int { get set }
var year: Int { get set }
init()
init(day: Int, month: Int, year: Int)
}
匿名 struct
struct Cake {
union {
int layers;
double height;
};
struct {
bool icing;
bool sprinkles;
} toppings;
};
转换方式同以上规则,可以使用以下两种方式初始化
var simpleCake = Cake()
simpleCake.layers = 5
print(simpleCake.toppings.icing)
let cake = Cake(
.init(layers: 2),
toppings: .init(icing: true, sprinkles: false)
)
因为 cake 的 union是匿名的,没有 label,所以直接用 .init 初始化
Function
c 定义
int product(int multiplier, int multiplicand);
int quotient(int dividend, int divisor, int *remainder);
struct Point2D createPoint2D(float x, float y);
float distance(struct Point2D from, struct Point2D to);
与其对应的 swift
func product(_ multiplier: Int32, _ multiplicand: Int32) -> Int32
func quotient(_ dividend: Int32, _ divisor: Int32, _ remainder: UnsafeMutablePointer<Int32>) -> Int32
func createPoint2D(_ x: Float, _ y: Float) -> Point2D
func distance(_ from: Point2D, _ to: Point2D) -> Float
指针类型
c 的指针类型
const Type * [TAB] UnsafePointer<Type>
Type * UnsafeMutablePointer<Type>
Type * const* UnsafePointer<Type>
Type * __strong * UnsafeMutablePointer<Type>
Type ** AutoreleasingUnsafeMutablePointer<Type>
const pvoid * UnsafeRawPointer
void * UnsafeMutableRawPointer
函数指针
int (*add)(int a, int b);
会转换成 如下的 block
@convention(c) (a: Int32, b: Int32) -> Int32