Minimal setup for C++ and Objective-C (Core Libraries) interop

biq
3 min readOct 16, 2020
Makes sense to show something Apple related here, right.

Intro

Going directly to source is sometimes the right move. On macOS that would be the core libraries using Objective-C. In this example, we use CoreWLAN to ask for information on the current wlan interface connection. You can find the complete source on github.

Setup

Structure

We have a makefile at project root level, organise our sourcefiles in a directory called src and will produce binaries in a directory called bin.

Making our lives easier

Let’s start by creating a makefile, which lets us manage building the project.

In the make target build, the first step is to create a dynamic library called libwlaninfo via the CXX compiler, which we have specified as clang. The -stdlib=libc++ flag ensures that the compiler links against libc++ (heavily favoured by Apple) and -std=c++11 tells the compiler to use the c++11 standard. Next we declare this operation to produce a dynamic library by specifying -shared. To get access to Apple’s core library, we have to link the appropriate libraries, which in our case is Foundation and CoreWLAN. The -fpic ensures that the library has relative address management. Finally we specify the Objective-C++ source file (indicated by the .mm extension) and tell the compile to put the output file in the bin directory. The next step is to compile our program entry (via the main function) contained in Main.cpp, link it with the dynamic library and put the executable in the bin directory.

Implementation

Defining the external library interface

The idea is, to create an interface which abstracts the fact, that we interact with a native Objective-C library and looks like plain old C. The main work will be done in GetCurrentWlanConnection. It returns a status code, which can be interpreted throught the enum WlanErrorCode and, if executing…

--

--