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

问题描述

我有一个名为DetectorResult的结构,它内部还有另一个结构称为detector_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;

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

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

class CDetectorResult(ctypes.Structure):
    _fields_ = [("detect_num",ctypes.c_int),("class_idx",("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,sizeof(*resultData));
        printf("memset 2");
        //memset(resultData->preds,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上运行它。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)