将 FILE* 指针从 Swift 传递给 C 函数

Pass FILE* pointer from Swift to C Function

我在 iOS Swift 项目中使用 libxml。要调试,我需要从 Swift:

调用以下 C 函数
void xmlDebugDumpString (FILE * output, const xmlChar * r)

但是,我不知道如何在 Swift 中创建 FILE * output 指针。

我尝试了以下代码:

let debugDoc: UnsafeMutablePointer<FILE>
debugDoc = fopen(debugDocURL.absoluteString, "w")
xmlDebugDumpNode(debugDoc, str)

代码编译正常,但出现以下运行时错误

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

问题是 absoluteString 的错误用法,所以 fopen() 失败并且 returns nil。从 URL 创建 C 字符串的正确方法是 withUnsafeFileSystemRepresentation:

guard let debugFile = debugDocURL.withUnsafeFileSystemRepresentation( { fopen([=10=], "w") }) else {
    // Could not open file ...
}

现在您可以写入文件了

xmlDebugDumpNode(debugFile, ...)

并最终关闭它:

fclose(debugFile)

另一种选择是将调试输出转储到(预定义的) “标准错误”文件:

xmlDebugDumpNode(stderr, ...)