Calling a C function in Python and returning 2 values

前端 未结 1 1042
既然无缘
既然无缘 2021-01-07 00:12

I am trying to figure out how to return 2 vales from a C function that I called in python. I have read through the material online and am using struct to output the two vari

相关标签:
1条回答
  • 2021-01-07 00:39

    Your C code is fine, the problem you are experiencing is in how you use python ctypes. You should tell that the function returns a struct re_val and not a double:

    calling_function.c_func.restype =  ctypes.c_double
    

    The above makes the function return a single double value in the eyes of ctypes. You should tell python that the function returns a structure:

    import ctypes as ct
    
    # Python representation of the C struct re_val
    class ReVal(ct.Structure):
        _fields_ = [("predict_label", ct.c_double),("prob_estimates", ct.c_double)]
    
    calling_function = ctypes.CDLL("/home/ruven/Documents/Sonar/C interface/Interface.so")
    calling_function.c_func.argtypes = [ctypes.c_char_p, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double]
    # and instead of c_double use:
    calling_function.c_func.restype = ReVal
    

    This way you tell python's ctypes that the function returns a aggregate object that is a subclass of ctypes.Structure that matches the struct re_val from the c library.

    NOTE Be very carefull with argtypes and restype, if you use these incorrectly it is easy to crash the python interpreter. Then you get a segfault instead of a nice traceback.

    0 讨论(0)
提交回复
热议问题