2

How to call c function "TIFFGetField" in swift.
Does anyone have an idea or give me a sample? Thanks

//The function declared
extern int TIFFGetField(TIFF* tif, uint32 tag, ...);

/* sample: in objective-c is working very well */
unsigned int width;
TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width);

/* sample: in swift failed */
var width: UInt32 = 0
TIFFGetField(tiff, uint32(TIFFTAG_IMAGEWIDTH), &width)

/* error message: 
 * 'TIFFGetField' is unavailable: Variadic function is unavailable
 */
CocoaUser
  • 1,361
  • 1
  • 15
  • 30
  • C-based variadic functions are not available in Swift. I haven't used `TIFFGetField` (in libtiff?), but you'd better try with `TIFFVGetField`. – OOPer Aug 13 '16 at 05:24
  • Hi OOPer, Yes libtiff. I also try to call TIFFVGetField. But I don't how to call this function in Swift. could you give me an example? – CocoaUser Aug 13 '16 at 05:28

1 Answers1

1

As noted in my comment, C-based variadic functions are not available in Swift. A good alternative in your case is using TIFFVGetField.

Just seeing the function signature and man docs, you may need to write something like this:

(Please see UPDATE.)

var width: UInt32 = 0
withUnsafeMutablePointer(&width) {widthPtr in
    let args: [CVarArgType] = [widthPtr]
    TIFFVGetField(tiff, UInt32(TIFFTAG_IMAGEWIDTH), getVaList(args))
}

(UPDATE) Sorry, I have been missing that Apple is saying this function getVaList should be avoided. In the recommended way, using withVaList, the code above can be rewritten as:

var width: UInt32 = 0
withUnsafeMutablePointer(&width) {widthPtr in
    withVaList([widthPtr]) {vaListPtr in
        TIFFVGetField(tiff, UInt32(TIFFTAG_IMAGEWIDTH), vaListPtr)
    }
}

(Thanks, Martin R.)

Please try.

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • See [`getVaList`](https://developer.apple.com/reference/swift/1539624-getvalist): *"WARNING: This function is best avoided in favor of withVaList, ..."*. Example here: http://stackoverflow.com/a/36898589/1187415. – Martin R Aug 13 '16 at 07:18