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

7
  • This is invalid *const argv[] , what are you trying to do? Commented Oct 29, 2015 at 1:51
  • @iharob Run this function ==> public func execvp(_: UnsafePointer<Int8>, _: UnsafePointer<UnsafeMutablePointer<Int8>>) -> Int32 Commented Oct 29, 2015 at 1:54
  • @iharob execvp(const char *file, char *const argv[]); Commented Oct 29, 2015 at 1:54
  • @Olaf I remove the tag Commented Oct 29, 2015 at 2:01
  • @iAdjunct This question has nothing to do about argv & argc it's something different. I'm trying to create an array with char pointers. Not duplicate. Commented Oct 29, 2015 at 2:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you @matt , but i need UnsafePointer<UnsafeMutablePointer<Int8>> not a UnsafeMutablePointer<UnsafePointer<Int8>> . UnsafePointer doesn't have alloc , UnsafeMutablePointer has. can you explain me how to make a UnsafePointer<UnsafeMutablePointer<Int8>> with this method ?
let cs2 : UnsafePointer<UnsafePointer<Int8>> = UnsafePointer(cs)
Why do you want to make the inner pointers mutable? In C strings, they are not.
I want to use a posix function in unistd : public func execvp(_: UnsafePointer<Int8>, _: UnsafePointer<UnsafeMutablePointer<Int8>>) -> Int32
Okay, I wrote it all out for you, but this is absolutely the last time. :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.