2017-02-11 106 views
0

我想集成一个函数与gsl。因此,我必须定义一个函数f(integrant必须是double (*)(double, void*)的形式)。对于gsl集成方法的调用,我需要定义一个结构体,它包含一个指向函数的指针(该结构体被称为gsl_function)。指向一个对象的成员函数的指针

gsl_function F; 
F.function = &MyClass::my_f; 

功能f必须在类(在相同的类从该积分过程应该被称为)来实现。我该如何分配上面正确的指针,因为2号线未编译和导致错误:

cannot convert ‘double (MyClass::*)(double, void*)’ to ‘double (*)(double, void*)’ in assignment. 

这里的my_f

struct my_f_params { double a; double b;}; 

    double my_f (double x, void * p) { 
    struct my_f_params * params = (struct my_f_params *)p; 
    double a = (params->a); 
    double b = (params->b); 
    return 1.0/(sqrt(a * (1.0 + x)*(1.0 + x)*(1.0 + x) + (1-a) * std::pow((1.0 + x), (3.0 * (1.0 + b))))); 
    } 
+0

您需要在那里提供'static'成员函数作为回调函数。我想''void *'参数可以被(错误)用来在必要时传递'this'指针。 –

+0

指向成员的指针不是普通的指针。你将不得不把它包装在一个平面的功能。 SO上有很多这种技术的例子。 –

+1

想一想'gsl_function :: function'的'void *'参数。它可能用于什么? –

回答

1

which has to be of the form double (*)(double, void*)

非静态成员函数声明的定义涉及隐含的通话范围限定符如错误消息中所述

double (MyClass::*)(double, void*) 
    // ^^^^^^^^^ 

这与回调函数指针定义不同。

你也许可以用这样的界面做的,是通过回调函数的void*参数传递this指针:

class MyClass { 
    static double func(double d,void* thisPtr) { 
     MyClass* myClass = (MyClass*)thisPtr; 
     // do something 
    } 
}; 

如前所述in the documentation你可以把params像在一个包装类:

class gsl_function_wrapper { 
public:  
    gsl_function_wrapper() { 
     F.function = &func; 
     F.params = this; 
    } 
private: 
    gsl_function F; 

    double a; 
    double b; 

    static double func(double d,void* thisPtr) { 
     gsl_function_wrapper* myWrapper = (gsl_function_wrapper*)thisPtr; 
     // do something with a and b 
     foo(d,myWrapper->a,myWrapper->b); 
    } 
}; 
+0

请提供正确的引用,告诉您获得此解决方案的位置(不在GSL网站上)。可能的正确来源 - https://stackoverflow.com/a/18413206/2472169 –

相关问题