Passing arrays to c functions

Giulio Genovese <[email protected]> Fri, 29 Jun 2012 02:25:37 -0400
Newsgroups gmane.comp.python.ctypes
Message-ID <CABDkqW59VsNBcV3G=BPbm6mM18GUPtfSod52EXauE1e30QKW6w@mail.gmail.com>
I have recently started to use ctypes to run some C code within python. To
pass an array to C code, if self is a numpy array, I found that a popular
solution is the one to use
self.ctypes.data_as(ctypes.c_void_p)
or
self.ctypes._as_parameter_
However, once profiling the python script, I realized that a lot of time
was being wasted in these three functions:
/usr/lib/python2.7/dist-packages/numpy/core/_internal.py:281(data_as)
/usr/lib/python2.7/ctypes/__init__.py:501(cast)
/usr/lib/python2.7/dist-packages/numpy/core/_internal.py:268(__init__)
The solution is not completely clear to me. I realized that, if a numpy
array needs to be fed to a C function multiple times, it pays off to create
a C array (with something like "(ctypes.c_double * n)()"), copy the
elements from the numpy array in the C array, and feed this array to the C
function. I am not sure why this is the case, as extracting a pointer from
a numpy array should be fairly straightforward. But I guess when invoking
the self.ctypes command, a ctypes object is constructed and this has a
non-trivial cost(?).
Is there something else that can be done? Overall, I find this misleading,
as this seems a popular way to use ctypes, while most people trying to pass
arrays to C functions do so to achieve maximum efficiency with the C code.
I am really not an expert, so please let me know if I am missing something.
Thanks,

------------------------------------------------------------------------------
Live Security Virtual Conference
Exclusive live event will cover all the ways today's security and 
threat landscape has changed and how IT managers can respond. Discussions 
will include endpoint security, mobile security and the latest in malware 
threats. http://www.accelacomm.com/jaw/sfrnl04242012/114/50122263/

_______________________________________________
ctypes-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/ctypes-users