[EMAIL PROTECTED] wrote:

> In my C-module I have a loop like this:
> ***********************************************
>
> int size=10000000;
>
> output=(double *) calloc(size, sizeof(double));
> py_output=PyList_New(0);
> for(i=0; i<size; i++){
>   tmp=PyFloat_FromDouble(output[i]);
>   PyList_Append(py_output, tmp);

     Py_DECREF(tmp); // append adds a reference

> }
>
> free(outout);
>
> return py_output;

or with proper error handling:

   int size=10000000;
   output=(double *) calloc(size, sizeof(double));
   if (!output) {
       PyErr_NoMemory();
       return NULL;
   }
   py_output=PyList_New(0);
   if (!py_output)
      goto error;
   for(i=0; i<size; i++){
     tmp=PyFloat_FromDouble(output[i]);
     if (!tmp)
         goto error;
     if (PyList_Append(py_output, tmp) < 0)
         goto error;
     Py_DECREF(tmp);
  }
  free(outout);
  return py_output;
error:
   Py_XDECREF(py_output);
   free(output);
   return NULL;

or optimized for speed:

   ...
   py_output = PyList_New(size);
   if (!py_output)
      goto error;
   for (i = 0; i < size; i++) {
       tmp = PyFloat_FromDouble(output[i]);
       if (!tmp)
         goto error;
       PyList_SET_ITEM(py_output, tmp);
       // don't decref here
   }
   ...


hope this helps!

</F>



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to