[C++-sig] question about using a python object from C++
Ralf W. Grosse-Kunstleve
rwgk at yahoo.com
Wed Jul 2 04:36:43 CEST 2003
--- Shi Sherebrin <shi at imaging.robarts.ca> wrote:
> I've spent a lot of time reading the Boost web pages, and I'm still
> mystified. I have a class that I built in Python. I want to use this
> class in C++. From reading about Boost it seems to allow bidirectional
> operation, but I can't find a simple (or any) example of using C++ to
> access a Python object. Could someone please point me in the right
> direction?
I am confused by your "ideal" example, but maybe this is useful:
Given sandbx/matrix.py:
class matrix:
def __init__(self, (n_rows, n_columns)):
self.n = (n_rows, n_columns)
Attached is the code that shows how you can create a sandbx.matrix.matrix
instance in C++. This is the test:
from sandbx_boost import to_matrix
m = to_matrix.to_matrix()
assert m.n == (2,3)
Ralf
P.S.: Sorry for all the namespace stuff. It is not essential. This is just what
I have.
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/tuple.hpp>
namespace sandbx { namespace {
boost::python::handle<>
import_module(const char* module_name)
{
using namespace boost::python;
return handle<>(PyImport_ImportModule(const_cast<char*>(module_name)));
}
boost::python::object
to_matrix()
{
using namespace boost::python;
object matrix_module(import_module("sandbx.matrix"));
object matrix = matrix_module.attr("matrix");
return matrix(make_tuple(2,3));
}
void init_module()
{
using namespace boost::python;
def("to_matrix", to_matrix);
}
}} // namespace sandbx::<anonymous>
BOOST_PYTHON_MODULE(to_matrix)
{
sandbx::init_module();
}
__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com
More information about the Cplusplus-sig
mailing list