Wednesday, October 30, 2024

Signals and Slots in C++ using Boost's Library...

 I remember in the early part of my Bangalore stay, two C++ libraries attracted me - Boost and Loki. However, with the daily grinding in the office, i never got time to deep dive into it. And finally i got a chance to look into the Boost library in 2007, during my stay in Japan. But it was difficult - without a proper hand holding. I just got a chance to delve into the Boost pointers. 

Today, i will discuss about another important aspect of Boost library - Signals and Slots. These are Boost's answer to publisher-subscriber or Observer pattern or as the Java people call it - the event listener pattern - and for all others - simply the event driven programming.

You should use this pattern in case of...

Event-Driven Programming:

Signals and slots are ideal for event-driven programming, where objects need to react to events triggered by other objects.

GUI Development:

Boost.Signals2 is commonly used in GUI development to connect UI elements to actions or events.

Decoupling Components:

Signals and slots allow you to decouple components of your application, making it easier to modify and maintain the code.

Example : 

The following example writes "Hello, World!" using signals and slots. 

Here are the two function objects.

class Hello

{

public:

void operator()() const

{

cout << "Hello";

}

};


class World

{

public:

void operator()() const

{

cout << ", World!" << endl;

}

};

Then, we create a signal sig1, a signal that takes no arguments and has a void return value. 

boost::signals2::signal<void()> sig1;

Next, we connect the hello and world function objects to the signal using the connect method.

boost::signals2::connection c1 = sig1.connect(hello);


boost::signals2::connection c2 = sig1.connect(world);


By default, slots are pushed onto the back of the slot

list, so the output of this program will be as expected.


Hello, World!


The way signals and slots are connected, they can

be disconnected as wellas we have done here.


c1.disconnect(); // Disconnect the Hello object


Signals can propagate arguments to each of the slots

they call. For instance, a signal that propagates mouse

motion events might want to pass along the new mouse

coordinates and whether the mouse buttons are pressed.


//Slot Arguments

void print_args(float x, float y)

{

cout << "The arguments are " << x << " and " << y << endl;

}


void print_sum(float x, float y)

{

cout << "The sum is " << x + y << endl;

}


void print_product(float x, float y)

{

cout << "The product is " << x * y << endl;

}


void print_difference(float x, float y)

{

cout << "The difference is " << x - y << endl;

}


void print_quotient(float x, float y)

{

cout << "The quotient is " << x / y << endl;

}


And this is how we create the signals


boost::signals2::signal<void (float, float)> sig;


sig.connect(&print_args);

sig.connect(&print_sum);

sig.connect(&print_product);

sig.connect(&print_difference);

sig.connect(&print_quotient);


sig(5., 3.);


And the output will be as follows:


The arguments are 5 and 3 The sum is 8 The product is 15 The difference is 2 The quotient is 1.66667


Here is the complete source code of my

exploration.


Enjoy...


//============================================================================

// Name : BoostSignal2Test.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

// Description : Hello World in C++, Ansi-style

//============================================================================


#include <boost/signals2/signal.hpp>

#include <iostream>

using namespace std;

class Hello

{

public:

void operator()() const

{

cout << "Hello";

}

};


class World

{

public:

void operator()() const

{

cout << ", World!" << endl;

}

};

//Slot Arguments

void print_args(float x, float y)

{

cout << "The arguments are " << x << " and " << y << endl;

}


void print_sum(float x, float y)

{

cout << "The sum is " << x + y << endl;

}


void print_product(float x, float y)

{

cout << "The product is " << x * y << endl;

}


void print_difference(float x, float y)

{

cout << "The difference is " << x - y << endl;

}


void print_quotient(float x, float y)

{

cout << "The quotient is " << x / y << endl;

}



int main() {

boost::signals2::signal<void()> sig1;


Hello hello;

World world;


boost::signals2::connection c1 = sig1.connect(hello);

boost::signals2::connection c2 = sig1.connect(world);


sig1();


    c1.disconnect(); // Disconnect the HelloWorld object

    cout << "c1 is disconnected\n";


    sig1();


    c2.disconnect();

    cout << "c2 is disconnected\n";

    sig1();



    //parameter passing


    boost::signals2::signal<void (float, float)> sig;


    sig.connect(&print_args);

    sig.connect(&print_sum);

    sig.connect(&print_product);

    sig.connect(&print_difference);

    sig.connect(&print_quotient);


    sig(5., 3.);


return 0;

}


Friday, October 11, 2024

Do you want your python code to access C/C++ code? use SWIG...

 SWIG (Simplifies Wrapper and Interface Generator) is an interface compiler that connects programs written in C and C++ with scripting languages such as Perl, Python, Ruby, and Tcl. It works by taking the declarations found in C/C++ header files and using them to generate the wrapper code that scripting languages need to access the underlying C/C++ code.

Using SWIG, you can replace the main() function of a C/C++ program with a scripting interpreter from which you can control the application. This adds quite a lot of flexibility and makes the program "programmable." 

SWIG allows C/C++ programs to be placed in a scripting environment that can be used for testing and debugging. For example, you might test a library with a collection of scripts or use the scripting interpreter as an interactive debugger.

With SWIG, different C/C++ programs can be turned into scripting language extension modules. These modules can then be combined together to create new and interesting applications.

SWIG is sometimes compared to interface definition language (IDL) compilers such as those you find with systems such as CORBA and COM. Although there are a few similarities, the whole point of SWIG is to make it so you don't have to add an extra layer of IDL specifications to your application.

SWIG requires little, if any, modifications to existing code. For the most part, it encourages you to keep a clean separation between C/C++ and its scripting interface.

The primary audience of SWIG is C/C++ programmers who want to add a scripting language component to their applications.

So... here we go...

My experimentation with SWIG...

I have made a Python interface for my existing Factory Pattern project written in C++. Here's the C++ code of the Factory Pattern.

Step I : Define the C++ project

/*

* Food.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef FOOD_H_

#define FOOD_H_

#include <string>


using namespace std;


class Food {

public:

virtual string getName() = 0;


virtual ~Food(){


}

};



#endif /* FOOD_H_ */




/*

* Biscuit.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef BISCUIT_H_

#define BISCUIT_H_


#include "Food.h"


class Biscuit: public Food {

public:

Biscuit();

string getName();

~Biscuit();

};


#endif /* BISCUIT_H_ */



/*

* Biscuit.cpp

*

* Created on: Mar 10, 2021

* Author: som

*/

#include <iostream>

#include "Biscuit.h"

using namespace std;



Biscuit::Biscuit() {

// TODO Auto-generated constructor stub

cout<<"Biscuit is made..."<<endl;


}


Biscuit::~Biscuit(){}



string Biscuit::getName(){

return "It's a Biscuit";

}



/*

* Chocolate.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef CHOCOLATE_H_

#define CHOCOLATE_H_


#include <iostream>

#include "Food.h"


class Chocolate: public Food {

public:

Chocolate();

virtual ~Chocolate();

string getName();

};



#endif /* CHOCOLATE_H_ */



/*

* Chocolate.cpp

*

* Created on: Mar 10, 2021

* Author: som

*/


#include "Chocolate.h"



Chocolate::Chocolate() {

// TODO Auto-generated constructor stub

cout<<"Chocolate is made..."<<endl;


}


Chocolate::~Chocolate() {

// TODO Auto-generated destructor stub

}


string Chocolate::getName(){

return "It's a Chocolate";

}



/*

* Factory.h

*

* Created on: Mar 10, 2021

* Author: som

*/


#ifndef FACTORY_H_

#define FACTORY_H_



#include <iostream>

#include <string>


#include "Biscuit.h"

#include "Chocolate.h"


using namespace std;


class Factory{

public:

static Factory* instance;

static Factory* getInstance();


Food* makeFood(const string& type);


private:

Factory(){}


// Delete copy constructor & assignment operator (Singleton pattern)

Factory(const Factory&) = delete;

Factory& operator=(const Factory&) = delete;

};

//Factory* Factory:: instance = NULL;



#endif /* FACTORY_H_ */




/*

* Factory.cpp

*

* Created on: Jan 30, 2025

* Author: som

*/

#include "Factory.h"

Factory* Factory::instance = NULL;


Factory* Factory:: getInstance(){

if(Factory::instance == NULL){

Factory::instance = new Factory();

}

return Factory::instance;

}


Food* Factory::makeFood(const string& type){

if(type.compare("bi") == 0){

return new Biscuit();

}

if(type.compare("ch") == 0){

return new Chocolate();

}


return NULL;

}


Step II : Define the interface (.i) file FactoryPatternSwig.i

%module FactoryPatternSwig
%{
#include "Factory.h"
%}
%include "std_string.i"
%include "Food.h"
%include "Biscuit.h"
%include "Chocolate.h"
%include "Factory.h"

Step III :

Run the command

swig -c++ -python FactoryPatternSwig.i

It will generate

FactoryPatternSwig.py and FactoryPatternSwig_wrap

Step IV :

Compile the Wrapper by running the following command...

g++ -fPIC -c Biscuit.cpp Chocolate.cpp Factory.cpp FactoryPatternSwig_wrap.cxx -I/usr/include/python3.8

and 

 g++ -shared -o _FactoryPatternSwig.so Biscuit.o Chocolate.o Factory.o FactoryPatternSwig_wrap.o

This will generate the  _FactoryPatternSwig.so 

shared object.


Once compiled, you can copy the _FactoryPatternSwig.so and put it inside a Python project. Don't forget to keep the FactoryPatternSwig.py file in the python workspace.

Now we can use this shared library as I have done in the python workspace...

import FactoryPatternSwig

factory = FactoryPatternSwig.Factory.getInstance()

biscuit = factory.makeFood("bi")
print(biscuit.getName()) # Expected: "Biscuit"

chocolate = factory.makeFood("ch")
print(chocolate.getName()) # Expected: "Chocolate"

And.... that's it. 

U will get the result on the Python console.

Enjoy...