Unexpected extension module behaviour
John Machin
sjmachin at lexicon.net
Wed May 24 22:37:46 EDT 2006
On 25/05/2006 12:09 PM, rimmer wrote:
> I'm writing an extension module in C in which I'm passing an array of
> floats from C to python. The code below illustrates a simple C
> function designed to output an array of floats.
>
> ---------
> extTest.c
> ---------
> #include <stdio.h>
>
> double *testArray(int nsamp) {
>
> double nums[10000];
> int i;
> double cumdata = 0.0;
>
> printf("%d\n", nsamp);
> for (i=0; i<=nsamp; i++) {
> printf("%d\n", i);
> nums[i] = cumdata;
> cumdata += 0.5;
> printf("%f\n", nums[i]);
> }
> return nums;
Your problem is right here. The array nums is local to the function.
You are returning a pointer to memory whose contents are utterly useless
once you return from the function. Depending on the architecture and the
compiler, the pointer may point outside the stack, maybe causing the
hardware to take exception when the pointer is dereferenced, or it may
be inside the stack, in which case the next few function calls are
liable to trash the contents.
> }
>
> Then I write a wrapper function to pass the data back and forth between
> C and Python.
Before you do that, test it with a simple C main()!!!
[snip]
> Here is where I'm stumped. I must be doing something wrong during the
> PyList_SetItem or the Py_BuildValue.
Yes, you may have problems there too, but I didn't bother reading that
far :-)
>
> Any ideas on fixing this problem ?
>
> Regards,
>
> Rimmer
>
More information about the Python-list
mailing list