NodeJS addon with C++ and Objective-C

I have finished the module a few days ago (and it does not work, check the previous post) so now it is a good time to show a bit of technical difficulties and solutions.

First things first – an introduction. What we want is a class (I think in JS more proper name is a  prototype) with a few methods:

  • StartScan – with callback for results.
  • StopScan
  • IsScanning
  • GetState – current state of bluetooth (on/off etc).

We start with a module file – obd_cougar_lib.cc, structure of binding.gyp was described before for that project so I won’t paste it again, this is the file:

https://github.com/killpl/obd_cougar/blob/master/cougar_bluetooth_lib/binding.gyp

I used nan as the whole internet recommended and ended with something like this:

Let’s divide it into parts and describe one by one. First we need a module to export information and module initialization information. First says what we want to export and second is a static function that creates that object:

We use two defines to achieve this – NODE_MODULE  with two parameters: module name and second is initialization function conveniently declared by macro NAN_MODULE_INIT  with one parameter – a name. We export here a class and a function – we don’t have to export just a one thing.

Then we need a class to export – let’s call it Cougar_Bluetooth and init from inside of Init – this is visible in the snippet above. Next create a class:

There  static NAN_MODULE_INIT(Init) method which initializes class by setting a class name with

and constructor (the “new” method) with:

Of course we need methods inside the class too:

Method static NAN_METHOD(New) is our constructor, but in JavaScript we have to take care also for the possibility of using the constructor without the new operator – we just call the constructor with provided arguments in that case. Also we have a static field to hold that constructor. There we use a trick to avoid initialization in another file – we don’t need this if it is static variable in static method, so we return a reference to that object:

Last but not least I will show you how we can create a method in the class, this time descriptions will be inline in code:

That’s all. I have tested callback with simple logger class (to log messages from the addon to JS console) and it works. There were no callback calls for scan, because my devices are not BLE.

Seems quite easy at this point, but believe me – it wasn’t. At least it is not when you don’t have a code that you can copy and paste or clone.

Leave a Reply

Your email address will not be published. Required fields are marked *