c中exp函数反转的函数指针

时间:2016-09-13 08:45:03

标签: c function-pointers

我正在尝试定义一个计算e ^ -x的函数指针。 类似于C#的东西:

    Func<double, double> f = x => Math.Exp(-x);

我做了类似的尝试,徒劳无功:

double(*negativeExp(double x))(double) {
    double eValue = exp(1);
    return  pow(eValue, -x);
}

任何想法。

2 个答案:

答案 0 :(得分:3)

该功能的代码是:

double f(double x)
{
    return exp(-x);
}

然后你可以创建一个指向该函数的指针。样品使用:

int main(void)
{
    double (*p)(double) = &f;

    printf("f(1) == %f", p(1));
}

答案 1 :(得分:0)

要添加答案,如评论中所述,不可能在C语言中编写lambda / closures并以C#中的方式捕获变量。

也没有课程,所以没有神奇的&#34;这个电话&#34;它会将实例引用传递给函数。这意味着你需要通过任何状态&#34;手动通过参数。所以,在C#中看起来像这样的东西:

public class SomeClass
{
     private int _someParameter;

     public SomeClass(int p) { _someParameter = p; }

     public int DoStuff(Func<int> process) => process(_someParameter);
}

// somewhere in main
var s = new SomeClass(5);
var result = s.DoStuff(x => x * 2);

在C中看起来像这样:

struct SomeClass
{
    int someParameter;
};

// all "member functions" need to get the "this" reference

void SomeClassInit(struct SomeClass *_this, int p)
{
    _this->someParameter = p;
}

int DoStuff(struct SomeClass *_this, int(*process)(int))
{
    return process(_this->someParameter);
}

int Process(int x)
{
    return x * 2;
}

// somewhere in main
struct SomeClass s;
SomeClassInit(&s, 5);
return DoStuff(&s, Process);
相关问题