python和ctypes,ctypes从嵌套结构返回错误的浮点值

2024-06-26 13:58:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为DetectorResult的结构,其中有另一个名为detector\u predictions\t的结构。该嵌套结构是指向结构的指针,而不是结构的值:

/// detector result structures
typedef struct _detector_predictions_t {
    float x1;
    float x2;
    float y1;
    float y2;
    float score;
} detector_predictions_t, *pdetector_predictions_t;

typedef struct _DetectorResult {
    int detect_num;
    int class_idx;
    pdetector_predictions_t preds; ///< all face detector predictions
} DetectorResult, *pDetectorResult;

我有正确定义上述c结构的python ctypes代码:

# prediction structs
class CDetectorPredictionsT(ctypes.Structure):
    _fields_ = [("x1", ctypes.c_float), ("x2", ctypes.c_float), ("y1", ctypes.c_float), ("y2", ctypes.c_float), ("score", ctypes.c_float)]

class CDetectorResult(ctypes.Structure):
    _fields_ = [("detect_num", ctypes.c_int), ("class_idx", ctypes.c_int), ("preds", ctypes.POINTER(CDetectorPredictionsT))]

我有一个函数,它返回指向DetectorResult结构的指针:

pDetectorResult p_model_getresult(uint8_t* data)
{
    printf("entering\n");
    //pDetectorResult resultData = (pDetectorResult)malloc(sizeof(*resultData));
    //resultData->preds = (pdetector_predictions_t)malloc(sizeof(*resultData->preds));
    pDetectorResult resultData = (pDetectorResult)calloc(1, sizeof(*resultData));
    resultData->preds = (pdetector_predictions_t)calloc(1, sizeof(*resultData->preds));
    if(resultData == NULL) {
        printf("resultdata malloc failed");
    } else if(resultData->preds == NULL) {
        printf("preds malloc failed");
    } else {
        printf("about to memset");
        //memset(resultData, 0, sizeof(*resultData));
        printf("memset 2");
        //memset(resultData->preds, 0, sizeof(*resultData->preds));
        printf("finished memset");
        printf("successfully made det result\n");
        model_getresult(resultData, data);
        printf("the first bb is %f %f %f %f %f\n", resultData->preds->x1, resultData->preds->x2, resultData->preds->y1, resultData->preds->y2, resultData->preds->score);
        printf("returning now\n");
    }
    return resultData;
}

我有python代码调用这个函数:

self.aml_lib.p_model_getresult.argtypes = [c_uint_p_type(self.width * self.height * self.channel)]
self.aml_lib.p_model_getresult.restype = ctypes.POINTER(CDetectorResult)

# ...

    def model_getresult(self, data, format):
        input_data = self.model_setinput(data, format)
        print("data s ", input_data[0], input_data[1], input_data[2])
        return self.aml_lib.p_model_getresult(input_data)

最后,我使用python代码检查结果:

    ret = aml_object.model_getresult(data, PIXEL_FORMAT).contents
    a = ret.preds.contents.x1

其中ret是直接来自c的DetectorResult结构

a的值是一些随机数,如1.25^25。当我用c打印值时(例如printf(“%f”,resultData->;preds->;x1)),结果不同,是一个介于0和1之间的数字

如何使a的值与c中printf中打印的值相同

我在linux上运行这个


Tags: selfdatamodelfloatctypes结构detectorprintf