C interop: passing null pointers to unwrapped unsafe pointers


#1

Is there a way in Swift 3 to pass a null pointer to a C function that
takes an implicitly unwrapped unsafe pointer? I understand that
pointer parameters in C that don't specify nullability are mapped to
implicitly unwrapped pointers in Swift 3. Since it's not uncommon for
existing unannotated C APIs to accept null pointers, I assume there
has to be a way other than creating my own bridge functions in C. I
hope I am not wrong.

I am a bit surprised that I couldn't find an answer to this, neither
on this list nor on stackoverflow, as I presume I am not the only one
with this problem. Sorry, if I missed something.

Cheers,
Ingo


(Joe Groff) #2

An implicitly unwrapped Optional is still an Optional. You can use `nil` to pass a null pointer.

-Joe

···

On Oct 7, 2016, at 7:02 AM, Ingo Maier via swift-users <swift-users@swift.org> wrote:

Is there a way in Swift 3 to pass a null pointer to a C function that
takes an implicitly unwrapped unsafe pointer? I understand that
pointer parameters in C that don't specify nullability are mapped to
implicitly unwrapped pointers in Swift 3. Since it's not uncommon for
existing unannotated C APIs to accept null pointers, I assume there
has to be a way other than creating my own bridge functions in C. I
hope I am not wrong.

I am a bit surprised that I couldn't find an answer to this, neither
on this list nor on stackoverflow, as I presume I am not the only one
with this problem. Sorry, if I missed something.


#3

Oh thanks, I fundamentally misunderstood how unwrapped optionals work.

···

On Fri, Oct 7, 2016 at 6:25 PM, Joe Groff <jgroff@apple.com> wrote:

On Oct 7, 2016, at 7:02 AM, Ingo Maier via swift-users <swift-users@swift.org> wrote:

Is there a way in Swift 3 to pass a null pointer to a C function that
takes an implicitly unwrapped unsafe pointer? I understand that
pointer parameters in C that don't specify nullability are mapped to
implicitly unwrapped pointers in Swift 3. Since it's not uncommon for
existing unannotated C APIs to accept null pointers, I assume there
has to be a way other than creating my own bridge functions in C. I
hope I am not wrong.

I am a bit surprised that I couldn't find an answer to this, neither
on this list nor on stackoverflow, as I presume I am not the only one
with this problem. Sorry, if I missed something.

An implicitly unwrapped Optional is still an Optional. You can use `nil` to pass a null pointer.

-Joe