1

I am trying to make a c style array of chars pointer like this:

*const argv[] 

I figured out i have to use UnsafePointer<UnsafeMutablePointer<Int8>>

but i don't know how to initialize it.

How can i map this normal Array to UnsafePointer<UnsafeMutablePointer<Int8>> :

let argv = ["/usr/bin/printf", "BBB"]

Thank you

Omid Yaghoubi
  • 169
  • 1
  • 9

1 Answers1

3

The easy way is to let Cocoa form the C strings for you:

let args = ["/usr/bin/printf","BBB"]
var cs = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(2)
for (ix,s) in args.enumerate() {
    cs[ix] = UnsafeMutablePointer<Int8>((s as NSString).UTF8String)
}
var cs2 : UnsafePointer<UnsafeMutablePointer<Int8>> = UnsafePointer(cs)

Beware; cs does not contain copies. Its pointers are pointing right into the strings in args.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thank you @matt , but i need UnsafePointer> not a UnsafeMutablePointer> . UnsafePointer doesn't have alloc , UnsafeMutablePointer has. can you explain me how to make a UnsafePointer> with this method ? – Omid Yaghoubi Oct 29 '15 at 03:03
  • 1
    `let cs2 : UnsafePointer> = UnsafePointer(cs)` – matt Oct 29 '15 at 03:08
  • Why do you want to make the inner pointers mutable? In C strings, they are not. – matt Oct 29 '15 at 03:09
  • I want to use a posix function in unistd : public func execvp(_: UnsafePointer, _: UnsafePointer>) -> Int32 – Omid Yaghoubi Oct 29 '15 at 03:11
  • Okay, I wrote it all out for you, but this is absolutely the last time. :) – matt Oct 29 '15 at 03:18
  • Thank you very much !! I find out UnsafePointer has a constructor that gives a UnsafeMutablePointer. Your answers are very helpful. Thank you. – Omid Yaghoubi Oct 29 '15 at 03:23
  • You're welcome, but I warn you again, it makes no sense with the code I've written to make the CStrings mutable. We are pointing into the Strings; you cannot mutate these. – matt Oct 29 '15 at 03:25