![](/img/trans.png)
[英]Passing arguments to scipy.LowLevelCallable while using functions in C
[英]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.