Embedding Python in C

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 5 01:32:32 CEST 2007


En Mon, 04 Jun 2007 11:58:38 -0300, <mistabean at gmail.com> escribió:

> Onwards to the problem, I have been having difficulty embedding a
> python module into my C/C++ program. (just a test program before
> moving on into the real thing). I have been making test runs using the
> codes from http://docs.python.org/ext/pure-embedding.html as a basic,
> but modifiying it now as a function inside my C/C++ code.
>
> Problem started when I started passing an array as an argument. The
> module also need an array as an argument, but somehow I can't make
> them to go pass the "input-error checking" of the module.
>
> The code for argument building and calling are as follows:
>
> void CallSnake(char ModName[], char FuncName[], double result[])
> {
>   ...
>   /*Some operations to import modname, and preping FuncName, all is
> ok*/
>   ...
>   /*Processing the result array and calling the function, problem
> time*/
>         pArgs = PyTuple_New(MAX_ELEMENT);

Should check for a NULL return value.

>         pArg = PyList_New(1);

Same here.

>         for (i = 0; i < MAX_ELEMENT; ++i)
>         {
>              pValue = Py_BuildValue("d", result[i]);

I'd use PyFloat_FromDouble here.

>              PyTuple_SetItem(pArgs, i, pValue);
>
>              if (!(*pArgs).ob_refcnt)

What do you expect from this? pArgs is a newly created tuple - unless you  
DECREF it explicitely, ob_refcnt should never be 0. (Also, the -> operator  
exists for exactly this usage).

>          PyList_SetItem(pArg, 0, pArgs);
>          pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL);

You didn't show us how you got pFunc here. Just to make it clear, you are  
calling pFunc with a single argument, which is a list that contains a  
single element, which is a tuple containing exactly MAX_ELEMENT float  
objects.

> Traceback
>        if x.ndim != 1; /*x is the input array, checking if it's a 1D*/
> AttributeError: 'list' object has no attribute 'ndim'

Python lists don't have a ndim attribute. Perhaps you want some kind of  
Numeric array? (ndarray?)

> I have been trying many call variations, but alas, I think the problem
> lies in the list building process. I have no problems calling a non-
> arrayed (albeit,still single) argument.

Yes, it appears that you are building a plain list but your code is  
expecting another kind of object. I'm unfamiliar with Numeric arrays, if  
that is what you need; perhaps someone else can help, or ask again in a  
Numeric-specific list.

-- 
Gabriel Genellina




More information about the Python-list mailing list