Boost logo

Boost :

From: kk71878 (kk71878_at_[hidden])
Date: 2002-03-11 15:03:18


I originally posted a problem on the group about getting Boost.Python
libraries working within an embedded interpreter in a C++ program...
I feel like I may have gotten closer to a solution. I think perhaps
the best option is not to create a shared library to import from the
interpreter, but actually create the library within the C++ source of
the parent program (this is actually more desirable for me since my
C++ datamodel resides here anyway.) At any rate, here's what I've
come up with...

I found this piece of code out on a website
(http://www.mcmillan-inc.com/embed2.html) and placed it in my code, it
worked!

/* now a method we need to expose to Python */
long inc(long i) {
  return ++i;
}

/* and the magic that exposes it - a builtin module */
/* first, the wrapper function */
static PyObject *py_inc(PyObject *self, PyObject *args)
{
  long i;
  if (!PyArg_ParseTuple(args, "l", &i))
    return NULL;
    return Py_BuildValue("l", inc(i));
  }

/* now the module's function table */
static PyMethodDef genius_methods[] = {
  {"inc", py_inc, 1, "a silly example method"},
  {NULL, NULL} /* sentinel */
};

/* Python will call this when the module is imported */
void init_pyextension()
{
  PyImport_AddModule("genius");
  Py_InitModule("genius", genius_methods);
}

And after my Py_Initialize() call, I run the init_pyextension()
function and it's ready.
From within my embedded interpreter, I can do the following now...

>>> from genius import *
>>>
>>> inc(20)
21

I noticed that in Boost.Python's module_builder.cpp file, the last
definition is as follows:

PyMethodDef module_builder::initial_methods[] = { { 0, 0, 0, 0 } };

So, I guess the Boost.Python library is assigning methods in a
different (probably more dynamic) way. Right? So, how can we
translate the above code into something we can use in Boost.Python?

Thanks,

--Kevin Killingsworth


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk