KairisCharm
KairisCharm

Reputation: 1373

How to create a "typedef to a function pointer" in C#?

I'm converting code from C++ to C#. I have this line:

typedef bool (*proc)(int*, ...);

Can I do that in C#?

Upvotes: 6

Views: 2077

Answers (2)

Krizz
Krizz

Reputation: 11542

Delegates are not strictly equivalent, but used for similar purposes.

Sample:

public delegate void DoSth(string message);

void foo(string msg) {
   // ...
}


void bar() {
  DoSth delg = foo;
  delg("tttttt");
}

If you are trying to invoke code from native C++ libraries using P/Invoke, you will need to take a look at GetDelegateForFunctionPointer and GetFunctionPointerForDelegate Method pair of functions.

Upvotes: 2

abelenky
abelenky

Reputation: 64682

Short answer: Yes.

Generally:
(untested... just an outline)

{
    bool AFunction(ref int x, params object[] list)
    {
        /* Some Body */
    }

    public delegate bool Proc(ref int x, params object[] list);  // Declare the type of the "function pointer" (in C terms)

    public Proc my_proc;  // Actually make a reference to a function.

    my_proc = AFunction;         // Assign my_proc to reference your function.
    my_proc(ref index, a, b, c); // Actually call it.
}

Upvotes: 3

Related Questions