Extending Python with C API
Sami Vaisanen
ensiferum_ at hotmail.com
Thu Oct 18 18:45:23 EDT 2007
On Thu, 13 Sep 2007 21:26:33 -0400, Carsten Haese wrote:
> On Thu, 2007-09-13 at 18:05 -0700, Thierry Masson wrote:
>> Hello,
>>
>> I'm trying to use the C API to extend Python. I've looked at various
>> books and web sites (including the docs at python.org) and I can't get
>> any of the samples to work. Below is a very minimalist example that
>> I'm trying to get working and I was wondering if someone could tell me
>> where I'm going wrong. It's probably something very obvious to those
>> familiar with this technique.
>>[snip...]
>> The setup script builds the library OK, and I've verified that
>> gtestmodule.so is getting created. But when I try to run a test script
>> ( test.py, above) that uses the library, I get this error:
>>
>> Traceback (most recent call last):
>> File "test.py", line 2, in ?
>> import gtestmodule
>> ImportError: ./gtestmodule.so: undefined symbol: PyBuildValue
>
> Your module C code uses an unknown function by the name of PyBuildValue.
> The actual name of the function you mean is Py_BuildValue.
>
> HTH,
void get_python_exception(string& message, string& traceback)
{
GIL g;
PyObject* type = NULL;
PyObject* value = NULL;
PyObject* trace = NULL;
PyErr_Fetch(&type, &value, &trace);
py_ref ref_type(type);
py_ref ref_value(value);
py_ref ref_trace(trace);
py_ref name(PyString_FromString("traceback"));
py_ref module(PyImport_Import(name.get()));
if (module)
{
py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
if (fun)
{
PyErr_Restore(type, value, trace);
ref_type.release();
ref_value.release();
ref_trace.release();
py_ref ret(PyObject_CallObject(fun.get(), NULL));
if (ret && PyString_Check(ret.get()))
{
char* str = PyString_AsString(ret.get());
message = str;
traceback = "traceback not available";
return;
}
}
}
message = "message not available";
traceback = "traceback not available";
}
str evaluates to "None", any ideas what gives here? I've also tried to
call the traceback with a different function, such as
PyObject_CallFunctionObjArgs but the result is still same.
Thanks
More information about the Python-list
mailing list