Both C and Swift favorite Hello everyone. In this article, let's consider how to handle char **
well in Swift.
As pointed out by the pioneers, it can be said that the mutual conversion between Swift's String
type and C'schar *
type is in place.
-Swift --Getting along well with UnsafePointer --Qiita -Write cat (1) with Swift's POSIX API --Qiita
If you know about String # withCString
and String # fromCString
, you should be able to conveniently use C system call library calls from Swift.
By the way, some C system call library calls take char **
as an argument, which is also available from Swift. For example, the type of the fifth argument ʻargv of Swift's
posix_spawn` is:
UnsafePointer<UnsafeMutablePointer<Int8>>>
This corresponds to char * const *
in C, but I don't think there is much debate about what to do when you want to convert this to [Stirng]
. After being at a loss, I decided to modify and use the CStringArray
class that had fallen into Gist.
CStringArray
The CStringArray class used this time is created as Cocoa Touch Framework and can be installed with Carthage.
CStringArray takes [String?]
As a constructor argument and can retrieve char * const *
with the member variable pointers
. The following is a usage example.
let argv = CStringArray(["/bin/ls", "-la" , "/", nil])
posix_spawn(&pid, argv.pointers[0], &action, nil, argv.pointers, nil)
Since pointers
is an array of ʻUnsafeMutablePointer , you can retrieve the number with
count` if necessary.
If you set & argv.pointers
, it will be compatible withchar **
, but if you rewrite pointers
in the implementation, a memory leak will occur, so I think it is safe to handle with char * const *
. ..
--This implementation: https://github.com/hnw/CStringArray/blob/master/CStringArray/CStringArray.swift --Original implementation: https://gist.github.com/neilpa/b430d148d1c5f4ae5ddd
Actually, it may be possible to solve it neatly without creating such a rugged class. I'm new to Swift, so I'm looking forward to hearing from professionals.
Recommended Posts