How to return array from C++ function to Python using ctypes

前端 未结 2 891
小蘑菇
小蘑菇 2020-12-02 18:54

I am using ctypes to implement a C++ function in Python. The C++ function should return a pointer to an array. Unfortunately I haven\'t figured out, how to access the array

相关标签:
2条回答
  • 2020-12-02 19:31

    Your python code will work after some minor modifications:

    import ctypes
    
    f = ctypes.CDLL('./library.so').function
    f.restype = ctypes.POINTER(ctypes.c_int * 10)
    print [i for i in f().contents] # output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Basically there are two changes:

    1. remove numpy-related code and ctypes.cast call since we don't need them.

    2. specify the return type to ctypes.POINTER(ctypes.c_int * 10).

      By default foreign functions are assumed to return the C int type, hence we need change it to the desired pointer type.

    BTW, returning a newed array from C code to Python code seems inappropriate. Who and when will free the memory? It's better to create arrays in Python code and pass them to C code. This way it's clear that the Python code owns the arrays and takes the responsibility of creating and reclaiming their spaces.

    0 讨论(0)
  • 2020-12-02 19:33

    function.cpp returns an int array, while wrapper.py tries to interpret them as doubles. Change ArrayType to ctypes.c_int * 10 and it should work.


    It's probably easier to just use np.ctypeslib instead of frombuffer yourself. This should look something like

    import ctypes
    from numpy.ctypeslib import ndpointer
    
    lib = ctypes.CDLL('./library.so')
    lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,))
    
    res = lib.function()
    
    0 讨论(0)
提交回复
热议问题