[swift-users] Problem calling a C function passing a void** from Swift 3

Quinn "The Eskimo!" eskimo1 at apple.com
Fri Sep 16 02:47:19 CDT 2016

On 15 Sep 2016, at 22:11, Lane Schwartz via swift-users <swift-users at swift.org> wrote:

> Can anyone help me get the equivalent functionality in Swift 3?

I think the main issue here is that, in Swift 3, unsafe pointers, in their various flavours, don’t explicitly support nil.  Rather, nil is modelled like it is for any other type, via `Optional`.  You can read all about this change in SE-0055 [1]

So, if you have an C API like this:

extern int HackAlloc(void ** bufPtrPtr, size_t bufSize);
extern void HackFree(void * bufPtr);

you can call it like this:

var buf: UnsafeMutableRawPointer? = nil
let result = HackAlloc(&buf, 1024)
if result == 0 {

This is very similar to what you currently have except that `buf` is explicitly made optional.

The other difference is that `buf` is a ‘raw’ pointer, which means you have to understand Swift 3’s type aliasing rules.  You can read about the details in SE-0107 [2] bug a good place to start is the “UnsafeRawPointer Migration” section of the Swift 3 migration guide.


Share and Enjoy
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

[1]: <https://github.com/apple/swift-evolution/blob/master/proposals/0055-optional-unsafe-pointers.md>

[2]: <https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md>

More information about the swift-users mailing list