简体   繁体   中英

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. I also define an extra argument and pass it to the user_data void pointer as following:

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:

#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. How can I change my scripts so I can access the extra argument in my c program?

@DavidRanieri's comment resolved my problem:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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