首页 > 解决方案 > 在 C 中,从函数返回 2 个变量

问题描述

基本上,我有一个打印出某些数字的 C 函数,并且我还希望该函数返回 2 个值。我已经尝试过使用struct,但我没有正确执行此操作,我不确定如何继续。我已经阅读了其他问题,并且我知道使用指针会更好,但我不确定如何使用。

我的C代码如下:

struct re_val
{
    double predict_label;
    double prob_estimates;
    predict_label = 5.0;
    prob_estimates = 8.0;
};

int c_func(const char* dir, double a, double b, double c, double d)
{
    double x[] = { a, b, c, d };

    printf("x[0].index: %d \n", 1);
    printf("x[0].value: %f \n", x[0]);

    printf("x[1].index: %d \n", 2);
    printf("x[1].value: %f \n", x[1]);

    printf("x[2].index: %d \n", 3);
    printf("x[2].value: %f \n", x[2]);

    printf("x[3].index: %d \n", 4);
    printf("x[3].value: %f \n", x[3]);

    return re_val;
}

最终,我只想调用一个能够打印出数组并返回predict_labeland的函数prob_estimates

我实际上是通过 ctypes 在 python 中调用这个函数,我的 python 函数包含在下面。

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]
calling_function.c_func.restype =  ctypes.c_double
y = calling_function.c_func("hello",1.1, 2.2, 3.1, 4.2)
print y

标签: pythoncpython-2.7return-valuectypes

解决方案


首先你需要定义你的结构:

struct re_val{
    float predict_label;
    float prob_estimates;
};

struct re_val然后你需要从你的函数中返回一个:

struct re_val c_func(const char* dir, float a, float b, float c, float d )
{
    /* ... all that stuff ... */

    struct re_val r;
    r.predict_label = 5.0f;
    r.prob_estimates = 8.0f;   
    return r;
}

所以完整的例子是:

struct re_val{
    float predict_label;
    float prob_estimates;
};

struct re_val c_func(const char* dir, float a, float b, float c, float d )
{

    /* ... all that stuff ... */

    struct re_val r;
    r.predict_label = 5.0f;
    r.prob_estimates = 8.0f;   
    return r;
}

int main(void)
{
    struct re_val r = c_func("",1.0f,2.0f,3.0f,4.0f);
    printf("predict_label=%.1f\n",r.predict_label);
    printf("predict_label=%.1f\n",r.prob_estimates);
    return 0;
}

在这里试试:http ://rextester.com/WRROW32352


推荐阅读