Skip to content

Instantly share code, notes, and snippets.

@rpatrik96
Created November 11, 2018 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpatrik96/cd7eba98aa3255b2fb20dfc1fd2172a3 to your computer and use it in GitHub Desktop.
Save rpatrik96/cd7eba98aa3255b2fb20dfc1fd2172a3 to your computer and use it in GitHub Desktop.
Code for the article "Reizinger Patrik: Python interfész kialakítása C++-alapú függvénykönyvtárhoz Boost.Python segítségével" - supported by Tempus Közalapítvány
#include <boost/python.hpp>
using namespace boost::python;
/************************************************************/
/* C++ code which will be ported to Python with Boost.Python*/
/************************************************************/
/****************************/
/* Porting template classes */
/****************************/
template <typename T>
class TemplateClass
{
public:
TemplateClass(T value) : m_x(value){}
T m_x;
}
template class TemplateClass<int>; // instantiating template classes is a crucial step
/****************************/
/* Function overloading in case of static functions*/
/****************************/
class StaticOverloadClass
{
public:
void static method(int x);
void static method(int x, int y) = 0;
};
/****************************/
/* Passing arguments for virtual functions */
/****************************/
class BaseClass
{
public:
virtual void virtual_f_new_syntax(int x) = 0;
virtual void virtual_f_old_syntax(int x) = 0;
};
class VirtualFunctionClass : public BaseClass
{
public:
virtual void virtual_f_new_syntax(int x) {std::cout(x);}
virtual void virtual_f_old_syntax(int x) {std::cout(x);}
};
/* virtual - new syntax */
void virtual_f_new_syntax(int x)
{
this->get_override("virtual_f_new_syntax")();
}
/* virtual – old syntax */
void virtual_f_old_syntax(int x)
{
return call<void>(this->get_override("virtual_f_old_syntax").ptr(), x);
}
/************************************************************/
/* Boost.Python code for conversion */
/************************************************************/
BOOST_PYTHON_MODULE(cpp2python)
{
/* Porting template classes */
class_<TemplateClass>("TemplateClass_int", init<int>());
/* Function overloading in case of static functions*/
class_<StaticOverloadClass>("StaticOverloadClass")
.def<void(*)(int)>("method", &StaticOverloadClass::method)
.def<void(*)(int, int)>("method", &StaticOverloadClass::method)
.staticmethod("method");
/* Passing arguments for virtual functions */
class_<VirtualFunctionClass>("VirtualFunctionClass")
.def("virtual_f_new_syntax", pure_virtual(&VirtualFunctionClass::virtual_f_new_syntax))
.def("virtual_f_old_syntax", pure_virtual(&VirtualFunctionClass::virtual_f_old_syntax));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment