[Numpy-discussion] ctypes, numpy-array
Albert Strasheim
fullung at gmail.com
Tue Jul 25 06:09:28 CDT 2006
Hey Lars
> -----Original Message-----
> From: numpy-discussion-bounces at lists.sourceforge.net [mailto:numpy-
> discussion-bounces at lists.sourceforge.net] On Behalf Of Lars Friedrich
> Sent: 25 July 2006 12:50
> To: numpy-discussion at lists.sourceforge.net
> Subject: [Numpy-discussion] ctypes, numpy-array
>
> Hello,
>
> I would like to work with some data using python/numpy. The data is
> generated with C. To bring the data from C to python, I would like to
> use ctype. I am using python 2.4.3 on a windows-System.
>
> To accomplish the described task, I have the following plan. Please tell
> me, if this is possible, respectively if there is a better way.
>
> 1) In C, I write a .dll, that has a function
> int foo(PyObject *arg)
>
> 2) In python, I generate a numpy-array with the appropriate size. e.g.
> a = zeros((3,3), dtype=int)
>
> 3) From python, I call my .dll-function with a as an argument:
> windll.mydll.foo(a)
What's might be happening here is that a.ctypes.data is in fact being passed
to your function via ctypes's from_param magic (check the ctypes tutorial
for details).
In [10]: x = N.array([])
In [11]: x.ctypes.data
Out[11]: c_void_p(15502816)
In [12]: x._as_parameter_
Out[12]: 15502816
> 4) In the foo-function in the C-.dll I cast the pointer and access the
> data-field.
> PyArrayObject *myPtr = (PyArrayObject*) arg;
> myPtr->data[0] = 1;
> return 0;
>
> However, when I do this, I get an "AccessViolationError writing
> 0x000000000"
So what's probably happening here is that you already have a pointer to the
array's data which you then cast to a PyArrayObject pointer. Dereferencing
myPtr->data is looking for a pointer inside the array's data, which contains
zeros.
Here's a few things to try:
- look at ctypes's PyDLL option if you want to pass around Python objects
- Write your function as:
int foo(int* x);
Then do something like this:
x = N.array([...], dtype=N.intc)
mydll.foo.restype = None
mydll.foo.argtypes = [POINTER(c_int)]
mydll.foo(x.ctypes.data)
This might also work:
x = N.array([...], dtype=N.intc)
mydll.foo.restype = None
mydll.foo(x)
Cheers,
Albert
More information about the Numpy-discussion
mailing list