开发者问题收集

从 Swift 调用 C 函数

2015-06-08
1233

我试图从 Swift 调用一个 C 函数,但我不知道如何定义变量来传递参数。

函数 c 是:

DBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, int * pnWidth, int * pnDecimals );

主要问题是 pszFieldNamepnWidthpnDecimals inout 参数。我试过 made :

var dbf:DBFHandle = DBFOpen(pszPath, "rb")
var fName:[CChar] = [] 
var fieldWidth:Int32 = 0
let fieldDecimals:Int32 = 0

let fieldInfo:DBFFieldType = DBFGetFieldInfo(dbf, i, fName, &fieldWidth, &fieldDecimals)

但它给了我一个错误

Cannot invoke 'DBFGetFieldInfo' with an argument list of type '(DBFHandle, Int32, [CChar], inout Int32, inout Int32)'
Expected an argument list of type '(DBFHandle, Int32, UnsafeMutablePointer<Int8>, UnsafeMutablePointer<Int32>, UnsafeMutablePointer<Int32>)'

有什么想法吗?

3个回答
UnsafeMutablePointer<Int8>, UnsafeMutablePointer<Int32>, UnsafeMutablePointer<Int32>

您需要将变量转换为方法签名所需的适当类型。

C 语法:

  • const Type *
  • Type *

Swift 语法:

  • UnsafePointer
  • UnsafeMutablePointer

Apple 在其《将 Swift 与 Cocoa 和 Objective-C 结合使用》参考资料中对此进行了介绍 位于此处

cjnevin
2015-06-08

C 语法 -----> Swift 语法

const Type * -----> UnsafePointer

Type * -----> UnsafeMutablePointer

输入的数量和类型应该相同

Hana Bzh
2015-06-08

要从字符串创建 UnsafeMutablePointer <Int 8 > ,请使用:

String(count: 10, repeatedValue: Character("\0")).withCString( { cString in
    println()
    // Call your function here with cString
})
Kametrixom
2015-06-08