| Jeff Abrahamson on 26 Jan 2006 22:35:31 -0000 |
|
I have a C function that I want to use from python. I've generally
used swig for this in the past, which has been very easy. This C
function, however, returns an array.
I'm beginning to think that the easiest way to do this is to let the
function return a blog (er, "swig object") and then write a couple
accessors (see below).
This email is a query if anyone sees an easier way. I see a lot of
wrapper function writing in my future otherwise...
Thanks.
Below the example C code, then the example of using it python.
/* Make an array of length num and fill it with the first num
Fibonacci numbers.
*/
int *array_of_int(int num)
{
int *a;
int i;
a = (int *)malloc(num * sizeof(int));
for(i = 0; i < num; i++)
if(i == 0 || i == 1)
a[i] = 1;
else
a[i] = a[i-1] + a[i-2];
return a;
}
int index_int_array(int *a, int i)
{
return a[i];
}
And then use it like this:
>>> import example
>>> example.array_of_int(5)
<Swig Object at _e88e1608_p_int>
>>> fib = example.array_of_int(6)
>>> for i in range(6):
... print i, example.index_int_array(fib, i)
...
0 1
1 1
2 2
3 3
4 5
5 8
>>>
--
Jeff
Jeff Abrahamson <http://www.purple.com/jeff/> +1 215/837-2287
GPG fingerprint: 1A1A BA95 D082 A558 A276 63C6 16BF 8C4C 0D1D AE4B
Attachment:
signature.asc ___________________________________________________________________________ Philadelphia Linux Users Group -- http://www.phillylinux.org Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce General Discussion -- http://lists.phillylinux.org/mailman/listinfo/plug
|
|