UnsafeMutablePointer <Int8> from a string in Swift

I use the dgeev algorithm from the LAPACK implementation in the Accelerate structure to calculate the eigenvectors and eigenvalues โ€‹โ€‹of the matrix. Unfortunately, the LAPACK functions are not described in the Apple documentation with a simple link to http://netlib.org/lapack/faq.html .

If you look at it, you will find that the first two arguments in dgeev are characters indicating whether to calculate eigenvectors or not. In Swift, it requests UnsafeMutablePointer<Int8> . When I just use "N" , I get an error message. The dgeev function and error are described in the following screenshot. enter image description here

What should I do to solve this problem?

+5
source share
2 answers

The "problem" is that the first two parameters are declared as char * and not as const char * , even if the lines are not changed by the function:

 int dgeev_(char *__jobvl, char *__jobvr, ...); 

displayed in Swift as

 func dgeev_(__jobvl: UnsafeMutablePointer<Int8>, __jobvr: UnsafeMutablePointer<Int8>, ...) -> Int32; 

A possible workaround is

 let result = "N".withCString { dgeev_(UnsafeMutablePointer($0), UnsafeMutablePointer($0), &N, ...) } 

Inside the block, $0 is a pointer to a zero-terminated char array with a UTF-8 string representation.


Note: dgeev_() does not change the lines pointed to by the first two arguments, so it should be declared as

 int dgeev_(const char *__jobvl, const char *__jobvr, ...); 

which will appear in Swift as

 func dgeev_(__jobvl: UnsafePointer<Int8>, __jobvr: UnsafePointer<Int8>, ...) -> Int32; 

in which case you can just call him

 let result = dgeev_("N", "N", &N, ...) 

because Swift strings are automatically converted to UnsafePointer<Int8>) as described in the String Value for UnsafePointer <UInt8> function parameter behavior .

+3
source

This is ugly, but you can use:

 let unsafePointerOfN = ("N" as NSString).UTF8String var unsafeMutablePointerOfN: UnsafeMutablePointer<Int8> = UnsafeMutablePointer(unsafePointerOfN) 

and use unsafeMutablePointerOfN as a parameter instead of "N".

+3
source

Source: https://habr.com/ru/post/1210796/


All Articles