c中exp函数的反函数指针
Function pointer for inverse of exp function in c
我正在尝试定义一个函数指针来计算 e^-x。
类似于 C# 等价物:
Func<double, double> f = x => Math.Exp(-x);
我做了类似的事情,但没有成功:
double(*negativeExp(double x))(double) {
double eValue = exp(1);
return pow(eValue, -x);
}
任何想法。
该函数的代码为:
double f(double x)
{
return exp(-x);
}
然后你可以创建一个指向那个函数的指针。示例使用:
int main(void)
{
double (*p)(double) = &f;
printf("f(1) == %f", p(1));
}
要补充答案,如评论中所述,不可能在 C 中编写 lambdas/closures 并像在 C# 中那样捕获变量。
也没有 类,所以没有神奇的 "thiscall" 可以将实例引用传递给函数。这意味着您需要通过参数手动传递任何 "state"。所以,在 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);
我正在尝试定义一个函数指针来计算 e^-x。 类似于 C# 等价物:
Func<double, double> f = x => Math.Exp(-x);
我做了类似的事情,但没有成功:
double(*negativeExp(double x))(double) {
double eValue = exp(1);
return pow(eValue, -x);
}
任何想法。
该函数的代码为:
double f(double x)
{
return exp(-x);
}
然后你可以创建一个指向那个函数的指针。示例使用:
int main(void)
{
double (*p)(double) = &f;
printf("f(1) == %f", p(1));
}
要补充答案,如评论中所述,不可能在 C 中编写 lambdas/closures 并像在 C# 中那样捕获变量。
也没有 类,所以没有神奇的 "thiscall" 可以将实例引用传递给函数。这意味着您需要通过参数手动传递任何 "state"。所以,在 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);