Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call c++ function pointer from c#

Is it possible to call a c(++) static function pointer (not a delegate) like this

typedef int (*MyCppFunc)(void* SomeObject);

from c#?

void CallFromCSharp(MyCppFunc funcptr, IntPtr param)
{
  funcptr(param);
}

I need to be able to callback from c# into some old c++ classes. C++ is managed, but the classes are not ref classes (yet).

So far I got no idea how to call a c++ function pointer from c#, is it possible?

like image 973
Sam Avatar asked Mar 18 '10 14:03

Sam


People also ask

How do you call a function with a function pointer?

Calling a Function Through a Function Pointer in Cusing function pointer (a) int area = (*pointer)(length); // 3. using function pointer (b) int area = pointer(length);

How do you use a pointer to a function in C?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.

Can we use pointer with function in C?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.

How do you call a pointer?

The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.


1 Answers

dtb is right. Here a more detailed example for Marshal.GetDelegateForFunctionPointer. It should work for you.

In C++:

static int __stdcall SomeFunction(void* someObject, void*  someParam)
{
  CSomeClass* o = (CSomeClass*)someObject;
  return o->MemberFunction(someParam);
}

int main()
{
  CSomeClass o;
  void* p = 0;
  CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p));
}

In C#:

public class CSharp
{
  delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg);
  public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg)
  {
    CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate));
    int rc = func(Obj, Arg);
  }
}
like image 130
Lars Avatar answered Oct 02 '22 19:10

Lars