Calling a C function from Swift

I'm trying to call a C function from Swift, but I don't know how to define variables to pass parameters.

Function c:

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

      

The main problem is pszFieldName

, pnWidth

and pnDecimals

inout parameters. I've tried doing:

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)

      

but it gives me error

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>)'

      

Any ideas?

+3


source to share


3 answers


UnsafeMutablePointer<Int8>, UnsafeMutablePointer<Int32>, UnsafeMutablePointer<Int32>

      

You need to convert the variables to the appropriate types required to sign the method.

C Syntax:

  • const Type *
  • A type *


Swift syntax:

  • UnsafePointer
  • UnsafeMutablePointer

This extends to Apple's use of Swift with Cocoa and Objective-C at the link located here .

+2


source


Syntax -----> Swift Syntax

const Type * -----> UnsafePointer



Type * -----> UnsafeMutablePointer

Input count and types must be the same

0


source


To build UnsafeMutablePointer<Int8>

from string use:

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

      

0


source







All Articles