calling c from python with ctypes: passing vectors

前端 未结 3 1948
忘了有多久
忘了有多久 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:41

    Based on @Sven Marnach's answer:

    #!/usr/bin/env python
    import ctypes
    import numpy as np
    from numpy.ctypeslib import ndpointer
    
    libf = ctypes.cdll.LoadLibrary('/path/to/lib.so')
    libf.f.restype = ctypes.c_double
    libf.f.argtypes = [ctypes.c_int, ndpointer(ctypes.c_double)]
    
    def f(a):
        return libf.f(a.size, np.ascontiguousarray(a, np.float64))
    
    if __name__=="__main__":
        # slice to create non-contiguous array
        a = np.arange(1, 7, dtype=np.float64)[::2]
        assert not a.flags['C_CONTIGUOUS']
        print(a)
        print(np.multiply.reduce(a))
        print(f(a))
    

    Output

    [ 1.  3.  5.]
    15.0
    15.0
    

    Removing np.ascontiguousarray() call produces the wrong result (6.0 on my machine).

提交回复
热议问题