3

I am trying to call a C function from Swift , but I do not know exactly how to define variables to pass parameters.

The function c is:

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

The main problem is pszFieldName, pnWidth and pnDecimals inout parameters. I tried 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)

but it gives me an 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?

iBhavin
  • 1,261
  • 15
  • 30

3 Answers3

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

You need to convert your variables to the appropriate types required by the method signature.

C Syntax:

  • const Type *
  • Type *

Swift Syntax:

  • UnsafePointer
  • UnsafeMutablePointer

This is covered by Apple in their Using Swift with Cocoa and Objective-C reference located here.

cjnevin
  • 311
  • 2
  • 8
0

C Syntax -----> Swift Syntax

const Type * -----> UnsafePointer

Type * -----> UnsafeMutablePointer

The number of input and the types should be the same

Community
  • 1
  • 1
Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
0

To create an UnsafeMutablePointer<Int8> from a string use:

String(count: 10, repeatedValue: Character("\0")).withCString( { cString in
    println()
    // Call your function here with cString
})
Kametrixom
  • 14,673
  • 7
  • 45
  • 62