【问题标题】:Pass FILE* pointer from Swift to C Function将 FILE* 指针从 Swift 传递给 C 函数
【发布时间】:2018-08-18 17:07:30
【问题描述】:

我在我的 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)

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

线程 1:致命错误:在展开可选值时意外发现 nil

【问题讨论】:

    标签: c swift file-pointer


    【解决方案1】:

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

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

    现在你可以写入文件了

    xmlDebugDumpNode(debugFile, ...)
    

    并最终关闭它:

    fclose(debugFile)
    

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

    xmlDebugDumpNode(stderr, ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 2017-08-30
      • 2013-04-28
      相关资源
      最近更新 更多