gpt4 book ai didi

c++ - 如何将 C++ 回调传递给 C 库函数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:08 25 4
gpt4 key购买 nike

我正在使用 C++ 开发我的代码,并想使用 MPFIT 非线性曲线拟合库,它是用 C 开发的,但允许用 C++ 编译。

例如我有一个名为“myClass”的类,这个类有一个函数myClass::Execute()

我将“mpfit.h”包含到 myClass.h 文件中。并尝试从 Execute() 调用一个名为 mpfit 的函数。

int status = mpfit(ErrorFunction, num1, num2, xsub_1D, 0, 0, (void *) &variables, &result);

问题是 ErrorFunction 是 myClass 的函数。所以当我尝试使用它时编译器会出错。我试图将 ErrorFunction 带出类对象,但这次我得到了下面给出的错误:

当 ErrorFunction 在类之外时出错:

Error 4 error C2664: 'mpfit' : cannot convert parameter 1 from 'int (__cdecl *)(int,int,double *,double,double *,void *)' to 'mp_func'

当 ErrorFunction 在类内部时出错:

Error   3   error C3867: 'myClass::ErrorFunction': function call missing argument list; use '&myClass::ErrorFunction' to

误差函数的定义:

int ErrorFunction(int dummy1, int dummy2, double* xsub, double *diff, double **dvec, void *vars)

如何调用此函数并将其解析为 C 函数 mpfit?

mp_func 定义为:

/* Enforce type of fitting function */
typedef int (*mp_func)(int m, /* Number of functions (elts of fvec) */
int n, /* Number of variables (elts of x) */
double *x, /* I - Parameters */
double *fvec, /* O - function values */
double **dvec, /* O - function derivatives (optional)*/
void *private_data); /* I/O - function private data*/

最佳答案

确保您的调用约定匹配。 C 库使用 C 调用约定,或 cdecl (__cdecl)。如果您在 C++ 中使用 mp_func typedef,它可能默认为编译器的标准调用约定,或 stdcall (__stdcall)。创建一个新的 typedef 或将其更改为以下内容:

typedef int __cdecl (*mp_func)(int m, /* Number of functions (elts of fvec) */
int n, /* Number of variables (elts of x) */
double *x, /* I - Parameters */
double *fvec, /* O - function values */
double **dvec, /* O - function derivatives (optional)*/
void *private_data); /* I/O - function private data*/

并且当您声明 ErrorFunction 时,也将其声明为 __cdecl:

int __cdecl ErrorFunction(int, int, double*, double *, double **, void *);

如果编译器在调用 mpfit 函数时仍然报错,您可以尝试使用 cdecl 将您的函数指针转换为 mp_func typedef:

int status = mpfit((mp_func)ErrorFunction, num1, num2, xsub_1D, 0, 0, (void *) &variables, &result);

关于c++ - 如何将 C++ 回调传递给 C 库函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10639829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com