def evalonarray(lambdastr, array, length=None, **kwargs):
"""
Evaluates a function on an array using machine code.
array can be a numpy array, a ctypes array or a pointer to an array.
In the latter case, the correct length must be specified.
array will be overwritten! Make a copy before to avoid this.
"""
# interpret arguments
if hasattr(array, 'ctypes'): # numpy array
pointer = array.ctypes.get_as_parameter()
length = len(array)
elif isinstance(array, ctypes.Array): # ctypes array
pointer = ctypes.byref(array)
length = len(array)
elif isinstance(array, ctypes.c_void_p): # ctypes pointer FIXME
pointer = array
assert isinstance(length, int) and not length < 0
else:
raise ValueError('array type not recognized')
# generate code
code = """
# include <math.h>
# define pi M_PI
# define e M_E
%s
void evalonarray(double *array, int length)
{
double* MAX;
for (MAX = array + length; array < MAX; array++)
{
*array = f(*array);
}
}
""" % genfcode(lambdastr, **kwargs)
# compile an run on array
run = _compile(code, fname='evalonarray',
fprototype=[None, ctypes.c_void_p, ctypes.c_int])
run(pointer, length)
#########
# TESTS #
#########
评论列表
文章目录