ctypes - Beginner

后端 未结 3 1941
情歌与酒
情歌与酒 2020-11-28 17:42

I have the task of \"wrapping\" a c library into a python class. The docs are incredibly vague on this matter. It seems they expect only advanced python users would implem

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 17:55

    The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

    Passing and returning an integer

    The C++ code for a function which takes an integer and adds one to the returned value,

    extern "C" int add_one(int i)
    {
        return i+1;
    }
    

    Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

    g++ -shared -o testlib.so -fPIC test.cpp
    

    The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

    import numpy.ctypeslib as ctl
    import ctypes
    
    libname = 'testlib.so'
    libdir = './'
    lib=ctl.load_library(libname, libdir)
    
    py_add_one = lib.add_one
    py_add_one.argtypes = [ctypes.c_int]
    value = 5
    results = py_add_one(value)
    print(results)
    

    This prints 6 as expected.

    Passing and printing an array

    You can also pass arrays as follows, for a C code to print the element of an array,

    extern "C" void print_array(double* array, int N)
    {
        for (int i=0; i

    which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

    import numpy as np
    
    py_print_array = lib.print_array
    py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                             flags='aligned, c_contiguous'), 
                               ctypes.c_int]
    A = np.array([1.4,2.6,3.0], dtype=np.float64)
    py_print_array(A, 3)
    

    where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

    1.4
    2.6
    3.0
    

提交回复
热议问题