[swift-users] Working with const char** with Swift 3
Kenny Leung
kenny_leung at pobox.com
Mon Sep 19 15:44:10 CDT 2016
Hi Ron.
Not sure if you just want to have an array of Strings, and are working entirely in Swift. If so, you can just do
func haveSwiftFun(data :[String]?) {
for string in data {
print(string)
}
}
If you’re looking to interface Swift with a C function that takes const char * const *, that is covered in this thread:
https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160815/002956.html <https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160815/002956.html>
-Kenny
> On Sep 19, 2016, at 12:19, Ron Olson via swift-users <swift-users at swift.org> wrote:
>
> Hi all-
>
> So I've been working on this for hours and I'm just stuck. In C I'd write something like:
>
> const char* a_string_array[] = {"aloha", "world", "from beautiful Waikiki Beach"};
> haveFun(a_string_array);
>
> and haveFun is:
>
> void haveFun(const char** data) {
> printf("%s\n", data[0]);
> printf("%s\n", data[1]);
> printf("%s\n", data[2]);
> }
>
> So I'm trying to do something similar in Swift 3-REL (working in Linux) and the best I've been able to come up with is:
>
> func haveSwiftFun(data: Optional<UnsafeMutablePointer<Optional<UnsafePointer<Int8>>>>, count:UInt32) {
> for _ in 0...count {
> if let parm = params?.pointee! {
> let tempBuf = String(cString: (UnsafePointer<Int8>(parm)!))
> print(tempBuf)
> }
> }
> }
>
> But I'm not actually iterating through the array, I'm just getting the first element count times.
>
> I've been all over the usual places on the web (SO, Apple Docs, etc.), and have cobbled together something like:
>
> let buffer = UnsafeBufferPointer(start:(params?.pointee!)!, count:count)
> let anArray = Array(buffer)
>
> which gives me an [Int8], but I can't figure out how to get the actual char array from the anArray elements, with the hope of turning each element into its own String.
>
> I'm feeling I've run off the rails here and am hoping somebody might have some info on how to properly deal with working with a const char** in Swift 3. I'm sure/not sure it'll be an obvious 'ah ha!' moment, but that moment seems very very far away. :(
>
> Thanks for any help,
>
> Ron
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160919/8e543d88/attachment.html>
More information about the swift-users
mailing list