PTL - C++ template library for python bindings

Main goal of this library is to simplify mechanism to write objects to Python using C++ classes. It is simple and fast. API is very similar to ATL/WTL.

Main features:
  • This library is free software.
  • Use C++ class to implement python object
  • Use class member functions to bind with PyObjectType
  • Use native Python API to allocate/free C++ classes
  • Simplify new type declaration and registration
  • Define a Python class that is a sub-class of a C++ class
  • Provide strong type checking at compile time
  • Full control of type conversion
  • Build small and efficient code
Requirements
  • C++0x (lambda,variadic templates).
  • Examples build and tested with GCC v4.6
  • Clang - is almost ready, whaiting for lambds (v3.1 ?)
  • MSVC - not tested. I guess, vc++11 should be okay.
Example #1. Define simple class
#include <Python.h>
#include <string>
#include "../ptl.hpp" // base class
#include "../ptl-conv.hpp" // automatic type converters

//example #1
class myObj: public ptl::base_type<myObj>
{
  std::string str;
public:
  myObj(): str("myObj pt_str"){}

  BEGIN_PYOBJECT_TYPE(myObj, ".myObj")
    DEF_PYOBJECT_STR_AUTO(toStr)
  END_PYOBJECT_TYPE()

protected:
  const char* toStr() const
  {
    return str.c_str();
  }
};

PyMODINIT_FUNC PyInit_ptl(void)
{
  static struct PyModuleDef _module = {
        PyModuleDef_HEAD_INIT,
        "ptl", NULL, -1, NULL, NULL, NULL, NULL, NULL};

  PyObject* m = PyModule_Create(&_module);

  REGISTER_PYOBJECT_TYPE(m, myObj, "myObj");

  return m;
}
Python
>>> import ptl
>>> m = ptl.myObj()
>>> print(m)
myObj pt_str
>>>
Example #2. Add method
//example #2
class myObj2: public ptl::base_type<myObj2>
{
public:
  myObj2(){}

  BEGIN_PYOBJECT_TYPE(myObj2, ".myObj2")
    DEF_PYOBJECT_STR_STR("myObj2 class")
  END_PYOBJECT_TYPE()

  BEGIN_METHODS(myObj2)
    DEF_METHOD_ARGS_AUTO("sum", doSum, "return a + b + c")
  END_METHODS()

protected:
  int doSum(int a, int b, int c) const
  {
    return a+b+c;
  }
};

// add REGISTER_PYOBJECT_TYPE(m, myObj2, "myObj2")
// to PyInit_ptl()

>>> ptl.myObj2().sum(2,3,5)
10
>>>
Example #3. Members and properties
class myObj3: public ptl::base_type<myObj3>
{
  int val;
public:
  myObj3(): val(0){}

  int finalConstruct(PyObject *args, PyObject *kwds)
  {
    static const char*const kwlist[] = {"value", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", (char**)kwlist, &val))
      return -1;
    return 0;
  }

  BEGIN_PYOBJECT_TYPE(myObj3, ".myObj3")
    DEF_PYOBJECT_STR_STR("myObj3 class")
  END_PYOBJECT_TYPE()

  BEGIN_MEMBERS(myObj3)
    DEF_MEMBER_AUTO("value", val, "value member")
  END_MEMBERS()

  BEGIN_PROPERTIES(myObj3)
    DEF_PROP_GET_AUTO("valuePlusOne", value_plus1, "return avlue + 1")
  END_PROPERTIES()

protected:
  int value_plus1()
  {
    return val + 1;
  }
};
>>> m=ptl.myObj3(55)
>>> m.value
55
>>> m.valuePlusOne
56
>>>