Using Swift to reference an external C function call that uses pointers

As a newbie to Xcode, I'm trying to use an external C call that uses pointers and I'm having a hard time finding a way to reference them in Swift. The initial call in C is defined as:

int32 FAR PASCAL swe_calc(double tjd, int ipl, int32 iflag, double *xx, char *serr)

      

where xx

is a pointer to a 6-pair array and serr

is a pointer to any error message

Swift sees this as:

int32 swe_calc(tjd: Double, ipl: Int32, iflag: int32, xx: UnsafeMutablePointer<Double>, serr: UnsafeMutablePointer<Int8>)

      

(from: https://github.com/dwlnetnl/SwissEphemeris/tree/master/SwissEphemeris )

The closest thing I tried even came close:

var serr : UnsafeMutablePointer<Int8> = nil; // returns any error messages from the call
var x  = [Double](count: 6, repeatedValue: 0); // array of 6 doubles returned from the call
var xx : UnsafeMutablePointer<Double> ;

xx = &x
swe_calc(2436647.0003794227, 4, 258, xx, serr)
println("xx = \(x[0]), \(x[1]), \(x[2]), \(x[3]), \(x[4]), \(x[5]), errors (if any)=\(serr)")

      

Line xx=&x

gives error

Cannot assign input value of type [(Double)] to value of type UnsafeMutablePointer

I need a way to get / reference / use the values ​​returned from xx

into an array of 6 doubles, and serr

definitely shouldn't be Int8

, but instead. (I can get other Java and C # versions to work, but Swift put me on my guard.)

How can I make a call swe_calc

to give him what he needs and figure out what I need?

+3


source to share


1 answer


You were close. Both parameters UnsafeMutablePointer

need an array of the appropriate type, passed as "inout argument" with &

:

var x  = [Double](count: 6, repeatedValue: 0);
var serr = [Int8](count: 1024, repeatedValue: 0)
let result = swe_calc(2436647.0003794227, 4, 258, &x, &serr)

      

Of course, arrays must be allocated large enough as expected by the C function.



If this function puts a null-terminated string in the buffer it points to serr

, then you can convert it to a Swift string with:

let errorString = String.fromCString(&serr)

      

+2


source







All Articles