[英]What is the best way to pass an extra argument to a scipy.LowLevelCallable function?
I have a python script that creates a set of ctype input arguments to pass to scipy.LowLevelCallable
(see the notes section) and uses it to make a call to scipy.generic_filter
that only executes a single iteration for testing purposes.我有一个 python 脚本,它创建了一组 ctype 输入 arguments 以传递给
scipy.LowLevelCallable
(请参阅注释部分)并使用它来调用scipy.generic_filter
,它只执行一次迭代以进行测试。 I also define an extra argument and pass it to the user_data
void pointer as following:我还定义了一个额外的参数并将其传递给
user_data
void 指针,如下所示:
from scipy import LowLevelCallable, ndimage
import numpy as np
import ctypes
clib = ctypes.cdll.LoadLibrary('path_to_my_file/my_filter.so')
clib.max_filter.restype = ctypes.c_int
clib.max_filter.argtypes = (
ctypes.POINTER(ctypes.c_double),
ctypes.c_long,
ctypes.POINTER(ctypes.c_double),
ctypes.c_void_p)
my_user_data = ctypes.c_double(12345)
ptr = ctypes.cast(ctypes.pointer(my_user_data), ctypes.c_void_p)
max_filter_llc = LowLevelCallable(clib.max_filter,ptr)
#this part only executes the LowLevelCallable function once and has no special meaning
image = np.random.random((1, 1))
footprint = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=bool)
mask = ndimage.generic_filter(image, max_filter_llc, footprint=footprint)
path_to_my_file/my_filter.so
corresponds to the scipy.LowLevelCallable
function argument structure and simply prints the user_data
variable: path_to_my_file/my_filter.so
对应于scipy.LowLevelCallable
function 参数结构并简单地打印user_data
变量:
#include <math.h>
#include <stdint.h>
#include <stdio.h>
int my_filter(
double * buffer,
intptr_t filter_size,
double * return_value,
void * user_data
) {
double x;
x = *(double *)(user_data);
printf("my user_data input is: %ld", x);
return 1;
}
This prints out my user_data input is: 0
, even though I defined my_user_data
as 12345
in my python script.这打印出
my user_data input is: 0
,即使我在 python 脚本中将my_user_data
定义为12345
。 How can I change my scripts so I can access the extra argument in my c program?如何更改我的脚本以便我可以访问我的 c 程序中的额外参数?
@DavidRanieri's comment resolved my problem: @DavidRanieri 的评论解决了我的问题:
printf("my user_data input is: %ld", x) --> printf("my user_data input is: %f", x), use %f for double (%ld is for long int)
printf("my user_data input is: %ld", x) --> printf("my user_data input is: %f", x),使用 %f 表示 double(%ld 表示 long int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.