繁体   English   中英

将额外参数传递给 scipy.LowLevelCallable function 的最佳方法是什么?

[英]What is the best way to pass an extra argument to a scipy.LowLevelCallable function?

我有一个 python 脚本,它创建了一组 ctype 输入 arguments 以传递给scipy.LowLevelCallable (请参阅注释部分)并使用它来调用scipy.generic_filter ,它只执行一次迭代以进行测试。 我还定义了一个额外的参数并将其传递给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对应于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;
}

这打印出my user_data input is: 0 ,即使我在 python 脚本中将my_user_data定义为12345 如何更改我的脚本以便我可以访问我的 c 程序中的额外参数?

@DavidRanieri 的评论解决了我的问题:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM