How to access and control the char *** in Swift

I have a C API looks like following:

int enumDataFormat(char ***SampleNames);

Swift Code:

------------------------------------------------------------------

var formats = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(1)

let count = enumDataFormat(&formats)

for index in 0..<count {

//Question in here: I don't known how to obtin the string in memory

}



Objective-C Code: It is working very well

------------------------------------------------------------------

char **formats;

int count = enumDataFormat(&formats);

if (count > 0) {

for (int i = 0; i < count; i++) {

//obtain the string from memory

char *formatString = *(formats + i);

NSLog(@"%s", formatString);

}

}

Given a C declaration like this:

extern size_t FullOfStars(char *** itemArrayPtr);

here's how you call it:

var itemArray: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
let itemCount = FullOfStars(&itemArray)

Note that you don't need to use

alloc
here, you can just initialise the value to nil.

I found two ways to access the elements. The first is kinda C-like.

var cursor = itemArray
for i in 0..<itemCount {
    print(String.fromCString(cursor.memory))
    cursor = cursor.successor()
}

The second is much Swift-ier (Swift-ish? Swift-ly? have we decided on an adjective yet?).

let b = UnsafeMutableBufferPointer(start: itemArray, count: itemCount)
for s in b {
    print(String.fromCString(s)!)
}

btw This was tested on Xcode 7.0b5, so YMMV on Xcode 6.4.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
How to access and control the char *** in Swift
 
 
Q