boost_python
Link:
http://www.boostpro.com/writing/bpl.html#hello-boost-python-world
libex8
#ifdef WIN32
#define DL_EXPORT __declspec(dllexport)
#else
#define DL_EXPORT
#endif
#include <Python.h>
#include <boost/python.hpp>
using namespace boost::python;
char const* greet(unsigned x)
{
static char const* const msgs[] = { "hello", "Boost.Python", "world!" };
if (x > 2)
throw std::range_error("greet: index out of range");
return msgs[x];
}
extern "C" // all Python interactions use 'C' linkage and calling convention
{
// Wrapper to handle argument/result conversion and checking
PyObject* greet_wrap(PyObject* args, PyObject * keywords)
{
int x;
if (PyArg_ParseTuple(args, "i", &x)) // extract/check arguments
{
char const* result = greet(x); // invoke wrapped function
return PyString_FromString(result); // convert result to Python
}
return 0; // error occurred
}
// Table of wrapped functions to be exposed by the module
static PyMethodDef methods[] = {
{ "greet", greet_wrap, METH_VARARGS, "return one of 3 parts of a greeting" }
, { NULL, NULL, 0, NULL } // sentinel
};
// module initialization function
DL_EXPORT void init_hello()
{
(void) Py_InitModule("hello", methods); // add the methods to the module
}
}
BOOST_PYTHON_MODULE(libex8)
{
def("greet", greet, "return one of 3 parts of a greeting");
}
/*
>>> import hello
>>> for x in range(3):
... print hello.greet(x)
...
hello
Boost.Python
world!
*/
/*
>>> import hello_ext
>>> print hello.greet()
hello, world
*/