Adding Class Variables To Object Orientated Inline::C

I’ve been working using the Perl module Inline::C lately.

I’ve been using it for some Object Orientated code, and I’ve had the need to have a shared class variable between various C classes. I thought I’d share how I’d accomplished this.

The code I’m using here is based on the object example in Inline::C-Cookbook.

I’m going to add a class variable called count to the example Soldier class.

Firstly we need to add a new line of code to declare this variable

## class variable
static int counter = 0;

Noticed I’ve made the variable static to ensure only one copy of it exists. I’ve also initialised it to 0.

One thing I’ve done, that isn’t really necessary is to add it to the Soldier object. The new Soldier object looks like this…

typedef struct {
char* name;
char* rank;
long serial;
int* count;
} Soldier;

The new line here is int* count, a pointer to an integer called count. We’ll point this at our static counter variable.

To point count to counter we modify the new function to add the following…

solder->serial = serial; ## existing code
soldier->count = &counter;

Here we’re specifically saying that our pointer count should point to the address of counter.

Great, but we need a way of accessing this data. We’ll create a new method called get_count to return the current value of count.

int get_count(SV* obj) {
return *((Soldier*)SvIV(SvRV(obj)))->count;
}

Great, now we can just call get_count from our Soldier object.

By itself this isn’t really much use as we never manipulate the value of counter. To prove this works, just modify the new method to add a line that increments counter. For example,

## increment counter
counter++;

Voila! We we have a static class variable that can now be used with Inline::C objects!