~xfl00d blog

stuff about code. mostly rants about things.

Wrapping C++ in Obj-C

So, guess it’s time for a short programming essay. I came across a C++ library these days, Crypto++, a very well-built library for cryptographic purposes. I needed a specific algorithm not implemented in Obj-C, so I wrote a quick wrap. Did some research and here’s what I have discovered.

Basically, you could choose to implement all the thing using Obj-C++, but that’s very messy and error-prone. Obj-C++ is very problematic and you should really stay away from it. The idea behind my wrapping technique is to keep the Obj-C and C++ files separated, and link them with an Obj-C++ file. Keeping the files separated and gluing them together with a third implementation works really well and keeps everything ordered.

We are also going to use opaque structs, since classes are basically structs in C++, so we can create an handy C++ object in Obj-C to handle all the calls, then release it when we are done. Ok, let’s get started.


Firstly, we need a CPP source files pair (header and implementation), in this example we are going to implement the AutoSeededRandomPool from Crypto++.

CPPRandomPoolHeader.h

class RandomPool_CPP {
    
public:
    int _generateRandomByte() {
        CryptoPP::AutoSeededRandomPool rng;
        return rng.GenerateByte();
    }
};

So far so good right? This only implements a method from the class, but it’s an example, however. I also packed all the code inside an header file, for brevity purposes. You should organize the code between an header and an implementation, that’s more readable and clean.

Now, we are going to write the actual Obj-C++ header and implementation, this will handle the C++ code and will be used by the Objective-C code.

OBJCPPRandomHeader.h

struct FRandomPool;

@interface RandomPool : NSObject {

    struct FRandomPool *_randomPool;

}

/*!
 * Generates a random byte.
 * \returns The newly generated random byte.
 */
-(int) generateRandomByte; // generates a random byte

@end

You can actually see that we are declaring the opaque struct here. The definition is there, but the implementation will be in the .mm file. We also declare a new ivar with the opaque struct. This will be the C++ handling object. Now, the Obj-C++ implementation:

OBJCPPRandomImplementation.mm

struct FRandomPool {
    
    RandomPool_CPP m1;
    
};

@implementation RandomPool

-(id) init {

    self = [super init];
    if(self) {
    
        _randomPool = new FRandomPool;
    
    }

    return self;
}

-(int) generateRandomByte {
    
    return _randomPool->m1._generateRandomByte();
    
}

@end

There you can see the actual struct body. It contains a RandomPool_CPP pointer. So, to access low-level C++ functions we can simply use the -> operator on the _randomPool object and call the methods, as you can see in generateRandomByte method. This is very handy, because all the memory management can be accomplished by handling that object.

Now, we can simply #import this Obj-C++ header into any other Obj-C file and use it. There:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
       
        RandomPool *rng = [[RandomPool alloc] init];
        NSLog(@"0x%x", [rng generateRandomByte]);
        
    }
    return 0;
}

And there you have it. C++ wrapped into Obj-C without messy source files. Last thing: if you are not using ARC, you can manually call dealloc, to release the Obj-C++ instance. With ARC enabled the method is called automatically. The dealloc should be also overrided to make it delete the _randomPool object and free the memory.

-(void) dealloc {
    
    delete _randomPool;
    
}

Thanks for the time, hope I helped you out. Feel free to leave a comment if you have any doubt/suggestion/report.

Clap – Issues

This article contains known Clap issues. You can submit one by writing to me@jndok.net.
Note: when a bug is written in blue, it means I have found a solution and the problem will be fixed in the next update. When it is written in red, there is no currently a fix in the update schedule.


version 0.1

  • Clap doesn’t work when the device is tilted in some positions (this is caused by the gravity force causing a moving false positive on the Z axis)
  • False positives are (sometimes) caused by knocks/taps on the table
  • False positives are caused by loud sounds in the ambient.

version 0.2

  • False positives are caused by loud sounds in the ambient.

Remember to check back here for updates!

Clap – An introduction

So what is Clap? How does it work? Clap it’s a MobileSubstrate tweak for iOS, designed to find your phone when you can’t remember where you put it. It happens (to me, at least :P) all the time. You put your phone down, go somewhere else, then go back, and you can’t find it anymore. Then you start throwing stuff around, looking under pillows, clothes, until you realize the phone is on your desk. You can’t tell me this didn’t happen to you at least two or three times.

Clap’s purpose is this. Well, I have planned some stuff for the future, like an Activator implementation, but that’s other stuff.


So, now you know what Clap does. But how does it do it? Clap listens (not continuously, only at a regular intervals) with your microphone for high-level sounds, if it detects one, it plays a short but loud alarm. It works only when your screen is shut off. But Clap is not a simple microphone listener. It features an accelerometer implementation, used to understand when and how fast your device is moving. This lets us avoid many false positives that can be bothering. It has a super comfortable switch to turn it off without even unlocking your phone. How? By using your phone’s ringer switch. You turn it to “silent” mode, and Clap magically turns off.

A little clarification: Battery usage

How is Clap doing with battery usage? Very well, indeed! The battery waste has been one of the first thing I thought about when coding Clap. The first BETA versions wasted about 10% battery in like 15 minutes. It was horrible. So, I did my best to fix this, and I succeeded.
The battery waste is almost imperceptible. I really cannot notice it on my iPhone 6.


So, this is the first version, and more stuff is planned to come. If you want to support me and buy Clap (for only $0.99 on BigBoss) go ahead! If you cannot buy it, for any reason, or just want to test it out, feel free to download a pirated copy. But please, if you like it and you are using it, consider buying to support me! Thanks for reading, and have a nice day.

If you want to contact me, for any reason: me@jndok.net

PS: Here is the official user guide for Clap.

Clap v0.1 – User Guide

   Introduction

Hi! First of all thanks for buying Clap. If you are here you will probably want to know more about the settings. I will explain in detail every setting for the o.1 version. Let’s start!

Hidden feature

iphone-6-ring-silent-switch

Before discussing the preferences sections, I wanted to tell you a quick feature that will make your life easier. Clap can occur into false positives. Not a big deal, but in some cases and places this could be tedious. So, when you want to quickly disable Clap, without going into the settings panel, simply put your phone in silent mode. You’ll avoid messages, calls and Clap triggering!

How to use Clap

Clap is very easy to use. The process starts only when you lock your device. After a few seconds, Clap is running and listening. If it detects a loud sound, it checks for some false positives filtering, and then it plays a short alarm. After the alarm, Clap resets after a defined amount of seconds (editable in the preference panel, see below).

Clap completely disables when you unlock the screen, so it doesn’t affect the battery when you are using your iDevice!

Issues

Every bug found by me (or by users) will be added in this article: Clap – Issues. Please check my email at the end of this article to submit a bug.

General Section

1

In the General section you’ll find a simple switch: Enabled. As you can probably figure out by yourself, this switch, when set to OFF, completely disables Clap, until you turn it back ON.

Switches

switched

In the Switches section you’ll find three switches: Disable When Ringer Switch is OFF, Disable When  Disable When Playing Music. The first one, if set to ON, disables Clap when the phone ringer switch is set to silent mode.

The second one, if set to ON, disables Clap when the iDevice is connected to a power source. When you pull off the AC, Clap starts working again.

The third one, if set to ON, disables Clap when playing music, and restarts it when the music is stopped.

Microphone

3

OK; we are now entering some more-advanced features. In the Microphone section, you will find three input field and a button: Trigger Value, Mic Update Interval and Reset Interval and Reset this section to default.

The first input field, Trigger Value, sets the minimum low pass amount to trigger the alarm. In simple words, this is the minimum sound peak that will trigger the alarm. The default value is 865 and it is the best value, in my opinion. Remember: the lower this value is, the lower the trigger sound will be. It can have values from 500 to 1000. If you use a value out of this range, the default value will be used by Clap.

The second input field, Mic Update Interval, sets the time to wait between the listening. The default value is 5000. It can have values from 1000 to 5000. If you use a value out of this range, the default value will be used by Clap. Note that a value closer to 1000 will make the detection easier, but will consume more battery.

The third and last input field, Reset Interval, sets the seconds to wait before turning Clap on again after a triggering. Clap disables when you unlock the phone, but it re-sets after a triggering. This field sets how long should pass before that re-set. The default value is 10 seconds. It can have values from to infinite.

The button simply resets all the three input fields to default. Note that you have to re-open the Clap settings panel to see the default values again.


Thanks for reading the Clap Guide. If you have any kind of problem/question/bug report/etc., contact me at me@jndok.net. Have a nice day!

A quick note about this blog.

What will be posted here?

I will use this nice blog to post all of the updates on my tweaks, guides, rants and other stuff I want to write when I don’t know what to do 😛

You can follow me on Twitter if you haven’t already: @_xfl00d.