[C++-sig] return PyObject* failed.
Qinfeng(Javen) Shi
shiqinfeng at gmail.com
Tue Sep 26 03:03:41 CEST 2006
Dear all,
I write a c extension function to access python list.
I can visit the list by PyObject* a, but failed when I tried to return
PyObject* to python.
Any suggestion will be appreciated.
>>> list1 = range(5);
>>> rlist = hello.testList(list1)
4 3 2 1 0 size:5
b is list type! # seems right now.
>>> rlist # but actually it
crashed when display the returned rlist
Segmentation fault
/**************c extension************/
static PyObject * testList(PyObject* a)
{
if(!(PyList_Check(a)))
{
printf("not list type!\n");
return NULL;
}
int num = PyList_Size(a);
PyList_Reverse(a);
// modify a.
for(int i=0;i<num;i++)
{
printf("%d ",PyInt_AsLong(PyList_GetItem(a,i))); // print
it out
}
printf("size:%d\n",num);
PyObject * b = PyList_New(10); // create
a new list b
if (b == NULL)
return NULL;
if(!(PyList_Check(b)))
// check b
{
printf("b is not list type!\n");
return NULL;
}
else
{
printf("b is list type!\n");
}
/**********************works untill now******************/
return (PyObject *)b; /***********failed**/ // return b. in
fact,if return a, it also crashed
}
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>
// Includes ====================================================================
#include <hello.c>
// Using =======================================================================
using namespace boost::python;
// Declarations ================================================================
BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(PyObject)
// Module ======================================================================
BOOST_PYTHON_MODULE(hello)
{
def("main", &main);
def("testList", &testList, return_value_policy< return_opaque_pointer >());
}
--
Qinfeng(Javen) Shi
Research School of Information Sciences and Engineering
Australian National University
Locked Bag 8001
Canberra ACT 2601
More information about the Cplusplus-sig
mailing list