python - 在 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_label
and的函数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
解决方案
首先你需要定义你的结构:
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;
}
推荐阅读
- python-3.x - 使用 Numba 时将多个输入传递给类时出错
- swift - 无法使用类型为“(范围)的参数列表调用“附加”
)' - r - R cor() 返回不对称结果
- java - 使用 H2OApi Java 绑定检索 H2O 帧摘要以 MalformedJsonException 结尾
- vba - 检查Access表中是否已经存在数据
- android - 如何将 TextEditInputLayout 恢复为原来的提示?
- c# - 未安装项目目标框架 4.7.1 和 4.7.2
- javascript - 如何根据 javaScript 中的条件从对象中删除值
- c++ - 在 C++ 中初始化对象
- typo3 - TYPO3 - 嵌套网格元素