calling c from python with ctypes: passing vectors

前端 未结 3 1946
忘了有多久
忘了有多久 2021-01-13 14:22

I want to call a c function from python using ctypes. From the documentation I don\'t understand how to pass pointer to vectors. The function I want to call is:



        
3条回答
  •  星月不相逢
    2021-01-13 14:49

    You can call it like this:

    #!python
    from ctypes import *
    
    #!python
    from ctypes import *
    
    # double f(int n, double* x)
    f = CDLL('/path/to/lib.so').f
    f.argtypes = [c_int, POINTER(c_double)]
    f.restype = c_double
    
    if __name__ == '__main__':
        array = (c_double * 5)(1, 2, 3, 4, 5)
        r = f(len(array), array)
        print(r)
    

    If you have numpy array, you can use numpy.array.ctypes.data_as:

    #!python
    from ctypes import *
    import numpy
    
    # double f(int n, double* x)
    f = CDLL('/path/to/lib.so').f
    f.argtypes = [c_int, POINTER(c_double)]
    f.restype = c_double
    
    if __name__ == '__main__':
        array = numpy.array([1, 2, 3, 4, 5])
        r = f(array.size, array.astype(numpy.double).ctypes.data_as(POINTER(c_double)))
        print(r)
    

    or:

    #!python
    from ctypes import *
    import numpy
    
    # double f(int n, double* x)
    f = CDLL('/path/to/lib.so').f
    f.argtypes = [c_int, POINTER(c_double)]
    f.restype = c_double
    
    if __name__ == '__main__':
        array = numpy.double([1, 2, 3, 4, 5])
        r = f(array.size, array.ctypes.data_as(POINTER(c_double)))
        print(r)
    

提交回复
热议问题