Objective-C到C函数的Swift转换

时间:2018-02-13 17:20:49

标签: objective-c swift

我在Objective-C到Swift转换方面遇到了困难。如何在Swift中编写下面的代码?

int mib[2];
size_t length;
mib[0] = CTL_HW;

mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physicalMemorySize, &length, NULL, 0);

mib[1] = HW_USERMEM;
length = sizeof(int64_t);
sysctl(mib, 2, &userMemorySize, &length, NULL, 0);

1 个答案:

答案 0 :(得分:1)

如果一个人知道两件事,那就不难了:

  • C int类型是32位整数,在Swift中是Int32, 不是Int
  • 来自C的
  • sizeof()在Swift中是MemoryLayout<T>.stride

然后我们得到:

var mib : [Int32] = [ CTL_HW, HW_MEMSIZE ]
var physicalMemorySize: Int64 = 0
var size = MemoryLayout<Int64>.stride
if sysctl(&mib, UInt32(mib.count), &physicalMemorySize, &size, nil, 0) == 0 {
    print(physicalMemorySize)
} else {
    print("sysctl failed")
}