Swift 是一种安全的语言,它对于可能引发危险的代码模式提供了严格的控制。其中之一就是对指针的使用。在 Swift 中,你不能直接使用指针,但你可以通过“Unsafe Pointers”来间接地使用它们。
Unsafe Pointers 主要用于和 C 语言交互,或者处理一些底层操作,比如直接操作内存。
let number = 42
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
pointer.initialize(to: number)
let value = pointer.pointee
print(value) // 输出 42
pointer.pointee = 50
let updatedValue = pointer.pointee
print(updatedValue) // 输出 50
使用完 Unsafe Pointer 后,记得释放它占用的内存。
pointer.deinitialize()
pointer.deallocate()
Swift 中的 Unsafe Pointers 主要用于与 C 语言交互。例如,如果你有一个 C 函数需要传入一个指针参数,你可以使用 Swift 的 Unsafe Mutable Pointer。
#include <stdio.h>
void modifyValue(int *value) {
printf("Value in C function before modification: %d\n", *value);
*value = 100;
printf("Value in C function after modification: %d\n", *value);
}
首先,你需要导入你的 C 代码。假设你的 C 代码在一个名为 myCFunctions.h
的头文件中,并且你使用桥接头文件 myCFunctions-Bridging-Header.h
来导入它。
在你的 Swift 文件中:
import Foundation
// 导入你的 C 代码的头文件
// 注意:这个头文件应该在你的桥接头文件中被引用过
let number = 42
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
pointer.initialize(to: number)
// 打印原始值
print("Value in Swift before calling C function: \(pointer.pointee)") // 输出 42
// 调用 C 函数来修改值
modifyValue(pointer)
// 打印修改后的值
print("Value in Swift after calling C function: \(pointer.pointee)") // 输出 100
// 不要忘记释放内存!
pointer.deinitialize()
pointer.deallocate()