Handle C char ** well in Swift

Both C and Swift favorite Hello everyone. In this article, let's consider how to handle char ** well in Swift.

Certainly the handling of char * in Swift is not bad

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, char ** is ...?

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:


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.


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 *. ..

Reference URL

--This implementation: https://github.com/hnw/CStringArray/blob/master/CStringArray/CStringArray.swift --Original implementation: https://gist.github.com/neilpa/b430d148d1c5f4ae5ddd

Request for opinions

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

Handle C char ** well in Swift
Pass C ++ char * to Swift
Create UnsafeMutablePointer <UnsafeMutablePointer <Int8>?>! In Swift for C char ** hoge
Handle pointers such as UnsafePointer <T> in Swift
Compare objects in Swift
[Swift] Get document Id as well as document in Cloud Firestore
Division becomes 0 in Swift
[Swift] Get key as well as value in Realtime database
Multidimensional array in Swift
Handle Enum in Mybatis TypeHandler
Photo library in Swift UI
Implement Swift UITextField in code
Reproduce Java enum in C #
Try mixing C and Swift in one project (OS X, Linux)
Defeat the hassle of treating C arrays as Tuples in Swift