首页 > 解决方案 > 转换 Int8?到不安全指针?

问题描述

我对 Swift 很陌生。尝试编写一个调用外部 C 方法的 Swift 应用程序。但是,Xcode 编译器给出了关于类型转换的错误。C 方法原型的形式为:

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。我使用了这个Obj-C 到 Swift 转换器,因为我几乎不了解 Swift,也无法阅读 Obj-C。我放入的 Obj-C 衬里是以下形式:

NSString * string1 = [[appBundle pathForResource:@"data" ofType:@""] stringByAppendingString:@"/"]; 
const char * string1Path = [string1 cStringUsingEncoding:[NSString defaultCStringEncoding]];

标签: cswiftxcode

解决方案


尽管将 an 转换Int8?为指针很简单(只需将其解包并&在将其作为参数传递时使用运算符),但您真正的问题是Int8首先将字符串转换为 an 是一个错误。返回的值Bundle.path(forResource:ofType:)将是一条路径,如下所示:

"/Applications/MyApp.app/Contents/Resources/Init.dat"

同时,您正在尝试将其转换为Int8,这是一种整数类型,可以存储从 -128 到 127 的值,使用带 a 的初始化程序String。这个初始化器返回一个可选值的原因是因为不是每个字符串都包含一个介于 -128 和 127 之间的数字,所以如果字符串是别的东西,你会得到nil.

"37"or这样的字符串"-101"会正确转换,但像上面这样的路径字符串总是只会给你nil.

您在这里真正想要做的是将您的转换String为 C 字符串。有几种不同的方法可以做到这一点,但我这样做的方法是使用URL'sfileSystemRepresentation功能,如下所示:

let url1 = appBundle.url(forResource: "Init", withExtension: "dat")! // instead of path
url1.withUnsafeFileSystemRepresentation { cPath in
    // cPath here is an UnsafePointer<Int8> that you can pass to C APIs inside this block.
}

// Don't let cPath get out here or bad things will happen.

请注意,您需要确保不要让此处cPath的块转义withUnsafeFileSystemRepresentation,因为它未定义为在该范围之外有效。

另请注意,由于 ,!如果该文件实际上不存在于您的应用程序中,这将使您的应用程序崩溃Init.dat,因此您最好确保包含它。


推荐阅读