使用void Pointers(Cuba Nint常规)时施放功能

Casting a function when using void pointers (CUBA Nint routine)

本文关键字:施放 功能 常规 Nint void Pointers Cuba 使用      更新时间:2023-10-16

老实说,我不是一个好程序员。我的任务是更改与古巴库的数值集成程序。但这不一定重要。我得到的是一个定制的例程,其中我具有许多可以集成,定义的功能:

    float spectra(float x[],float)

传递给数字维加斯例程

    float integrate ( float (*fxn)(float[],float), unsigned long ncall, int itmx )

致电

    integrate(spectra,ncall,itmx);

然后将其传递到实际例程。这一切都很好。

现在,在古巴例程中,我与:

进行集成
Cuhre(NDIM, NCOMP, Integrand, USERDATA, NVEC, ... ,integral, ...);

重要的是intemandand是函数,而用户达塔是一个空隙指针,可以传递您需要集成的任何额外内容。有点像GSL例程。

我不想重写所有"光谱"功能以使古巴例程具有适当的形式。我只想在中间包装。

Integrand具有铸件:

    static int Integrand(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata);

wher xx []是输入,(目前只有1个),ff []是输出(也是1)。UserData是我需要打字的空隙指针。

我的目标是制作一个包装器,以使程序中的任何地方都在调用:集成(功能,...)我可以按照我的意愿替换IntegrateCuba(功能,...)

我的尝试是将Integrand函数定义为一个空白模板,该模板将传递给UserData,该模板是输入到此float函数的类型铸造,然后从那里开始。我在下面的声明中说什么?

static int Integrand(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata) {
    #define f ff[0]
    float xxx[ndim];  //xx is inputs, ff is outputs
    xxx[0] = xx[0];   //ndim is 1 for now.
    //here I try to cast this void pointer
    float (*fxn)(float[],float) = NULL;

     // What do I put here??????
    *fxn = ???

    f = fxn(xxx,0.0);
    return f ;
}

最后,我将有一个例程:

float integrateCUBA ( float (*fxn)(float[],float), unsigned long ncall, int itmx )
{
    int comp, nregions, neval, fail;
    cubareal integral[NCOMP], error[NCOMP], prob[NCOMP];
    Cuhre(NDIM, NCOMP, Integrand, &fxn, NVEC, ...

我通过用户数据指针发送的地方"& fxn"。

我希望我很清楚。我要做的是,我要做的是将指针传递到函数" float(*fxn)(float [],float)",然后通过空隙指针进行正确的键入。

此代码是用C/C 编写的(我以外的其他人来自一堆旧的科学代码的可怕的混蛋。)它将在C 11中编译,因此,如果有一种简单的静态铸造方法那个也是。

非常感谢您的任何建议!

您应该只能施放,但是语法在不可读方面:

float (*fxn)(float[],float) = (float (*)(float[],float)) userdata;
                       // or static_cast<float (*)(float[],float)>(userdata);
f = fxn(xxx,0.0);

使用Typedef可以提高可读性:

typedef float (*Function)(float[],float);
Function fxn = (Function) userdata;