c++ - 如何将 C++ 函数指针(非静态成员函数)传递给预定义的 C 函数?

标签 c++ c templates function-pointers

我正在考虑使用来自 http://users.ics.forth.gr/~lourakis/levmar/ 的库,这是用 C 语言编写的。

但是我将它包含在一个成员函数“dlevmar_der”中,它期望两个函数指针作为它的参数:

int dlevmar_der(
    void (*func)(double *p, double *hx, int m, int n, void *adata), 
    void (*jacf)(double *p, double *j, int m, int n, void *adata),  
    double *p,         /* I/O: initial parameter estimates. On output contains the estimated solution */
    double *x,         /* I: measurement vector. NULL implies a zero vector */
    int m,             /* I: parameter vector dimension (i.e. #unknowns) */
    int n,             /* I: measurement vector dimension */
    int itmax,         /* I: maximum number of iterations */
    double opts[4],
    double info[LM_INFO_SZ],
    double *work,
    double *covar,
    void *adata
)

我有以下带有两个非静态成员函数 CallBack 和 MyJac 的简化模板类。 (假设我在类中也有所有其他属性 m_solution、m_info 等):

Template<class F> 
class MyClass
{
    public: 
        typedef void (MyClass<F>::*FuncPtrType)(float*);

        void Start()
        {
            this->Run(&MyClass<F>::MyJac);
        }

    protected:
        void Callback(ValueType x[], ValueType result[], int m, int n, void* adata){ // some code }
        void MyJac(ValueType x[], ValueType result[], int m, int n, void* adata){ // some code }

        void Run(FuncPtrType func)
        {
             int iterCount = dlevmar_der(&MyClass<F>::Callback, func,
        (double*)&this->m_solution[0],
        (double*)&zero[0],
        this->m_function.NumberOfParameters,
        this->m_function.NumberOfFunctionValues,
        this->m_maxIterations,
        this->m_options,
        this->m_info,
        NULL,
        NULL,
        static_cast<void*>(this));
        }
}

然而,当调用 Start() 时,我在“运行”函数中遇到错误功能,说:error C2664: 'slevmar_der' : cannot convert from 'void (__thiscall MyClass<F>::* )(float *,float *,int,int,void *)' to 'void (__cdecl *)(float *,float *,int,int,void *)

我的问题是 dlevmar_der 是否函数只能将函数指针指向静态成员函数?或者有什么方法可以将非静态成员函数与 dlevmar_der 一起使用实现?

最佳答案

您需要构建一个蹦床功能。

只需将 this 作为 adata 参数传递,然后编写一个回调函数,将 adata 转换回正确类型的指针并调用该方法.例如:

  void myFunc(double *p, double *hx, int m, int n, void *adata) {
      MyClass *self = static_cast<MyClass>(adata);
      self->funcMethod(p, hx, m, n, self->func_adata);
  }

关于c++ - 如何将 C++ 函数指针(非静态成员函数)传递给预定义的 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20042387/

相关文章:

c++ - 文字运算符模板 : why not string?

c++ - 符合标准的 C assert() 可以多次评估其参数吗?

php - 如何使用自定义 ERROR 500 模板和 EventListener 报告 Symfony2 生产中的错误?

c++ - 根据调用的构造函数更改成员数

c++ - 模板类中没有名为 X 的类模板

c++ - 如何让 map 容器使用不同的构造函数创建一个新对象?

c++ - 奇怪的编译器错误 : "undefined reference to ' main'"

c++ - 如何使用设置和使用 iconv 库

c - 一维访问多维数组 : is it well-defined behaviour?

c++ - 从应用程序打开控制台