Python and C

Paul Prescod paul at prescod.net
Sat Feb 21 14:15:34 EST 2004


hermes at numericable.fr wrote:

> Hi, this may be a newbie question, as I'm quite new to python but I'd rather get
> your points of view instead of wasting a week or two on a wrong way 
> 
> I'm using python 2.3 on a mandrake brand new system 
> 
> My problem : I'd like to use a complex C program under python. 
> After few researchs I tested SWIG, which seems to work for me exept that I'd
> like to be able to 
> use a C function under python that has this prototype 
> 
> void Fitimp(double *x1, double *x2... ) 

How will the implementation of Fitimp know how long these lists are?

> these double parameters are lists of double precision number.
> The python script will read this datas from files, So i'd like to know how to
> transform a python list of double precision float to a C double * variable

I don't know SWIG but I do know Pyrex, so here's a Pyrex solution:

import array

cdef extern from "header.h":
         cdef void Fitimp(double *x1, int x1_len, double *x2, int x2_len)

def PyFitimp(pyx1, pyx2):
         cdef double *x1, *x2
         cdef int address1, length1, address2, length2

         array1 = array.array('d', pyx1)
         address1, length1 = array1.buffer_info()
         x1 = <double *>address1

         array2 = array.array('d', pyx2)
         address2, length2 = array2.buffer_info()
         x2 = <double *>address2

         print x1[0]
         print array1
         print x2[0]
         print array2

         Fitimp(x1, length1, x2, length2)

PyFitimp(range(3,10), range(6,13))

  Paul Prescod






More information about the Python-list mailing list