Coder256 Coder256 - 2 years ago 93
Objective-C Question

C++ and Swift Don't Like Each Other

I am trying to use a C++ library named MP4v2 in Swift. It is mostly working in that I can can call some functions, use some classes, etc.

I am having trouble with a particular function that returns a void pointer. It is

on failure, or some other value on success. There is a constant defined to check with, but neither that nor checking for nil works.


/<path_to_project>/main.swift:19:12: Use of unresolved identifier 'MP4_INVALID_FILE_HANDLE'
, but it is DOES exist (other constants work).

if file != NULL
just causes the same problem, and
if file != nil
never is true, even if the function failed. What am I doing wrong?

Answer Source

Looking at MP4v2 documentation, here is the definition of the macro to check for invalid handle:

 #define    MP4_INVALID_FILE_HANDLE   ((MP4FileHandle)NULL)

The reason it cannot be used in Swift is because it involves a NULL. In fact, if you define something like

#define MY_NULL NULL

in your Objective-C(++) code and try to use it in Swift, Swift will suggest that you use nil instead.

The handle type MP4FileHandle is

typedef void *  MP4FileHandle

So, if you are calling a function like

MP4FileHandle aCPPFunction()

You should be able to check the return value as follows in Swift:

let h : MP4FileHandle = aCPPFunction()

if h != nil
   // The handle is valid and can be given as an argument to
   // other library functions.
   // The handle is NULL

I understand you tried this. It should work, please double-check. If for whatever strange reason this doesn't work for you, there are some other options:

  1. Write a simple helper function in C, C++, Objective-C or Objective-C++ to check if the handle is valid and return a integer flag, which should be easily understood by Swift.
  2. Check h.hashValue. If it is 0, then the handle is invalid, otherwise it is valid. This is a bad undocumented hack, but it has worked for me. I would stay away from this one.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download