[C++-sig] passing a dynamic PyObject * from C++ to Python
F. Oliver Gathmann
gathmann at cenix-bioscience.com
Wed Jun 25 18:16:52 CEST 2003
I have a function that reads a file and returns (depending on the
content of the file) either a Foo or a Bar wrapped in a PyObject*
(both Foo and Bar objects are expensive to copy and have to be passed
via a smart pointer).
With Boost.Python v1 I was able to do
PyObject * readFile(char const * fileName)
{
PyObject * obj;
FileInfo info(fileName);
if (info.isFoo())
{
std::auto_ptr<Foo> foo(new Foo(info.data()));
obj = to_python(foo);
}
else
{
std::auto_ptr<Bar> bar(new Bar(info.data()));
obj = to_python(bar);
}
return ref(obj);
}
and wrap this like so:
BOOST_PYTHON_MODULE_INIT(vigracore)
{
module_builder this_module("reader");
this_module.def(&readFile, "readFile");
}
With Boost.Python v2, I have not been able to find an equivalent
solution; I tried various approaches gathered from the Boost.Python
FAQ and documentation, e.g.
template <class T>
T identity(T x)
{
return x;
}
template <class T>
object get_pointer_reference(T x)
{
object f = make_function(&identity<T>,
return_value_policy<manage_new_object>()
);
return f(x);
}
object readFile(char const * fileName)
{
FileInfo info(fileName);
if (info.isFoo())
{
Foo * fooPtr = new Foo(info.data());
return get_pointer_reference(fooPtr);
}
else
{
Bar * barPtr = new Bar(info.data());
return get_pointer_reference(barPtr);
}
}
BOOST_PYTHON_MODULE(reader)
{
def("readFile", &readFile);
}
which compiles fine but crashes at runtime (using gcc 3.2.2 on Linux
with a recent CVS version of Boost).
Any hints that might help me solving this mystery would be much
appreciated!
Oliver
--------------------------------------------------------------------
F. Oliver Gathmann, Ph.D.
Director IT Unit
Cenix BioScience GmbH
Pfotenhauer Strasse 108 phone: +49 (351) 210-2735
D-01307 Dresden, Germany fax: +49 (351) 210-1309
fingerprint: 8E0E 9A64 A07E 0D1A D302 34C2 421A AE9F 4E13 A009
public key: http://www.cenix-bioscience.com/public_keys/gathmann.gpg
--------------------------------------------------------------------
More information about the Cplusplus-sig
mailing list