2016-09-13 10 views
0

e^-xを計算する関数ポインタを定義しようとしています。 C#の同等に類似 何か:cの逆関数の関数ポインタ

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

任意のアイデア:

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

私のような何かをすることによって、無駄にしようとしました。

+0

をなぜあなたは関数ポインタを返すされていますか? – 2501

+0

ラムダをCで定義することはできず、確かに変数を取得できないことに注意してください。だからあなたの問題は、関数の型を宣言する方法ではなく、本体です。 – Groo

+0

サイドノート:関数本体で単に 'exp(-x)'を呼び出さなかったのはなぜですか? –

答えて

3

関数のコードは次のようになります。

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

その後、あなたはその関数へのポインタを作ることができます。サンプル使用:

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

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

'double(* p)(double)=&f;'と 'double(* p)(double)= f;'の間に違いはありますか? – Pierre

+1

@Pierre違いはありません。 – mch

0

コメントで述べたように、答えに追加するには、それはC言語でラムダ/クロージャを書くと変数にあなたがC#で行うような方法をキャプチャすることはできません。

クラスも存在しないので、関数へのインスタンス参照を渡す魔法の "thiscall"はありません。つまり、パラメータを介して手動で「状態」を渡す必要があります。だから、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);