Skip to content

Instantly share code, notes, and snippets.

@siddharthpaliwal
Last active November 6, 2020 21:07
Show Gist options
  • Save siddharthpaliwal/80e982098e0e7330f6682bee57e7e720 to your computer and use it in GitHub Desktop.
Save siddharthpaliwal/80e982098e0e7330f6682bee57e7e720 to your computer and use it in GitHub Desktop.
Calling C++ functions from python
Calling C++ functions from python
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
/*
* C++ project sample to create a class and wrap it using BOOST::PYTHON library
* to be able to interface from python
*/
//Class/Struct to be exposed to python
class Hello{
private:
std::string msg;
public:
//Hello(std::string msg): msg(msg) {} //overloaded constructor
std::string greet(){
//std::cout << "Hello World!\n";
return msg;
}
//Set the message string
void set(std::string text){
this->msg = text;
}
int len; //public data member
};
//Raw cpp function
char const* greeter(){
return "hello World! from outisde class";
}
namespace python = boost::python;
//Boost.Python wrapper defining the module name, classes and methods
BOOST_PYTHON_MODULE(hello_ext){
python::class_<Hello>("Hello")
//.def(init<double, double>()) //another constructor if defined
.def("greet",&Hello::greet)
.def("set",&Hello::set)
//.def_readonly("len", &Hello::len)
.def_readwrite("len", &Hello::len)
;
python::def("greeter", greeter);
}
#Makefile to create a shared library of the module
# location of the Python header files
PYTHON_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)
# location of the Boost Python include files and library
BOOST_INC = /usr/include
BOOST_LIB = /usr/lib
# compile mesh classes
TARGET = hello_ext
$(TARGET).so: $(TARGET).o
g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so
$(TARGET).o: $(TARGET).cpp
g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).cpp
#! /usr/bin/env python
"""
Test script to call the greeter functions and Hello World class obects defined in a CPP module
"""
import hello_ext
print(hello_ext.__dict__)
print(hello_ext.greeter())
planet = hello_ext.Hello()
print(planet.greet())
planet.set("howdy")
print(planet.greet())
planet.set("Hello World!")
print(planet.greet())
@pktiuk
Copy link

pktiuk commented Nov 6, 2020

After attempt of building using make I get error:
Makefile:11: *** missing separator. stop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment