我对 Swift 很陌生。尝试编写一个调用外部 C 方法的 Swift 应用程序。但是,Xcode 编译器给出了有关类型转换的错误。 C 方法原型(prototype)的形式为:
void * cMethod(const char* string1Path, const char* string2Path, const char* string3Path, const char* string4Path);
Swift 代码的要点是:
import OpenGLES
import CoreGraphics
import GLKit
var mGLUTWindow: Void?
class myClass {
mGLUTWindow = nil
let appBundle = Bundle.main
let string1 = appBundle.path(forResource: "Init", ofType: "dat")
let string1Path = Int8((string1?.description)!)
let string2 = appBundle.path(forResource: "autostart", ofType: "type")
let string2Path = Int8((string2?.description)!)
let string3: String? = appBundle.path(forResource: "data", ofType: "") ?? "" + ("/")
let string3Path = Int8((string3?.description)!)
mGLUTWindow = cMethod(UnsafePointer(string3Path), string1Path, string2Path, "ios")
}
编译器给出错误:
Cannot convert value of type 'Int8?' to expected argument type 'UnsafePointer<Int8>?'
C 方法由桥接头引入。有没有办法将其转换为预期的参数?
注意:这里的 Swift 代码是从几年前的 Objective-C 文件中引入的,并且正在适应 Swift。我用过this Obj-C 到 Swift 转换器,因为我几乎不懂 Swift,也无法阅读 Obj-C。我放入的 Obj-C 内衬的形式为:
NSString * string1 = [[appBundle pathForResource:@"data" ofType:@""] stringByAppendingString:@"/"];
const char * string1Path = [string1 cStringUsingEncoding:[NSString defaultCStringEncoding]];
最佳答案
如果给我 C 函数和一些显示为 Objective-C 行的代码,我会写如下内容:
var mGLUTWindow: UnsafeRawPointer?
class MyClass {
func aMethod() {
let appBundle = Bundle.main
let string1 = appBundle.path(forResource: "Init", ofType: "dat")!
let string2 = appBundle.path(forResource: "autostart", ofType: "type")!
let string3 = (appBundle.path(forResource: "data", ofType: "") ?? "") + ("/")
mGLUTWindow = UnsafeRawPointer(cMethod(string3, string1, string2, "ios"))
}
}
在 Swift 中,当您将 String
传递给 char *
类型的参数时,Swift 会生成一个临时 C 字符串缓冲区并传递该缓冲区的地址,您有无需调用类似 const char * string1Path = [string1 cStringUsingEncoding:[NSString defaultCStringEncoding]];
的内容。
如果cMethod
保留任何指针供以后使用,您可能需要更复杂的代码,但不清楚我们是否需要像当前描述那样复杂的代码。
关于转换 Int8?到 UnsafePointer<Int8>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55622764/