Tyler Durden
Tyler Durden

Reputation: 1228

Function pointer translation from C++ to C#

I was translating some C++ code to C# and there was a function pointer within a structure definition, say func*

This func* was a pointer to a lot of other function pointers all contained within a C++ header file (This header file won't be translated).

Is there a way to translate this?

Code snippet:

struct CK_FUNCTION_LIST {
int version; 
/* Pile all the function pointers into it. */
#include "pkcs11f.h"
};

The class which I wish to translate contained a member of typeCK_FUNC_LIST*.

Upvotes: 1

Views: 418

Answers (3)

Zac Howland
Zac Howland

Reputation: 15872

If you are porting the code, you have a couple of options in C#:

1) Use lamdas (e.g. unnamed delegates). If these are 1-off functions (e.g. they are only used once), this will be the best choice.

2) Use named delegates. These will behave very similarly to C++ function pointers. If you are using the same functions in several places, this will be the better choice.

Just for clarification (as Ben Voigt pointed out): these are effectively the same thing as the lamda syntax will create a delegate for you.

The delegate type can be framework-provided (Action, Func, Predicate) or user-declared, and the delegate can be created inline (lambda, anonymous delegate) or by naming a method.

Upvotes: 2

BlueMonkMN
BlueMonkMN

Reputation: 25601

To demonstrate what you usually do when you want to use the equivalent of function pointers in C#, take a look at this:

struct MyFunctions {
  public Func<int,string,bool> ptr1;
  public Action<int> ptr2;
}

class Program
{
  static void Main(string[] args)
  {
     MyFunctions sample = new MyFunctions() { ptr1 = TestValues, ptr2 = DoThing };
     sample.ptr1(42, "Answer");
     sample.ptr2(100);
  }

  static bool TestValues(int a, string b)
  {
     Console.WriteLine("{0} {1}", a, b);
     return false;
  }

  static void DoThing(int a)
  {
     Console.WriteLine("{0}", a);
  }
}

The output is:

42 Answer
100

Upvotes: 2

Magus
Magus

Reputation: 1312

The normal way of using function pointers in C# is to declare an Action or Func. These are type safe, so they will only accept methods matching the signature of the type arguments.

Delegates are more generic (Action and Func are just specific named ones) but less clear. Really, we'd need more information to be any more specific.

Upvotes: 0

Related Questions