在 C++ 中调用 C 函数

call c function in c++

本文关键字:函数 调用 C++      更新时间:2023-10-16

我尝试创建一个包装类来包装库中的 c 函数lmdif1 cminpack

class CSolver
{
public:
    void solve()
    {
        ...
        using namespace std::placeholders;
    auto f = std::bind(&CSolver::fcn, this, _1, _2, _3, _4, _5, _6);
        int32_t iRet = lmdif1(f, 0, m_iEqualCount, m_iUnknownVariableCount, x, fvec, tol, iwa, wa, lwa);
    }
private:
    int32_t fcn(void* p, int32_t m, int32_t n, const double* x, double* fvec,int iFlag)
    {
    ....
    }
};

编译错误:

error: cannot convert ‘std::_Bind<std::_Mem_fn<int (CSolver::*)(void*, int, int, const double*, double*, int)>(CSolver*, std::_Placeholder<1>, std::_Placeholder<2>, std::_Placeholder<3>, std::_Placeholder<4>, std::_Placeholder<5>, std::_Placeholder<6>)>’ to ‘cminpack_func_mn {aka int (*)(void*, int, int, const double*, double*, int)}’ for argument ‘1’ to ‘int lmdif1(cminpack_func_mn, void*, int, int, double*, double*, double, int*, double*, int)’
         int32_t iRet = lmdif1(f, 0, m_iEqualCount, m_iUnknownVariableCount, x, fvec, tol, iwa, wa, lwa);

我该如何解决?

编辑:所以我将使用全局函数。谢谢大家。

不能获取成员函数的函数指针。它必须是一个类函数。类函数在 C++ 中使用 static 关键字声明。因此,您所要做的就是将fcn的原型更改为:

static int32_t fcn (void *p, int32_t m, int32_t n, const double *x, 
   double *fvec, int iFlag)

当然,您将无法从 fcn 中访问任何非静态成员变量。

希望这有帮助!