18

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?

Sam
  • 28,421
  • 49
  • 167
  • 247
  • I think your best bet is to create a C++/CLI wrapper for that. – Anzurio Mar 18 '10 at 15:26
  • This worked for me, https://stackoverflow.com/questions/39790977/how-to-pass-a-delegate-or-function-pointer-from-c-sharp-to-c-and-call-it-there/39803574#39803574 – Navin Pandit Nov 09 '17 at 07:30

2 Answers2

17

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);
  }
}
Sam
  • 28,421
  • 49
  • 167
  • 247
Lars
  • 6,421
  • 1
  • 23
  • 24
3

Have a look at the Marshal.GetDelegateForFunctionPointer method.

delegate void MyCppFunc(IntPtr someObject);

MyCppFunc csharpfuncptr =
    (MyCppFunc)Marshal.GetDelegateForFunctionPointer(funcptr, typeof(MyCppFunc));

csharpfuncptr(param);

I don't know if this really works with your C++ method, though, as the MSDN documentation states:

You cannot use this method with function pointers obtained through C++

Sam
  • 28,421
  • 49
  • 167
  • 247
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    The description says: "You cannot use this method with function pointers obtained through C++" - sadly, my function pointer is a c++ pointer. – Sam Mar 18 '10 at 14:27
  • 1
    Then your only option is, I guess, to create managed (ref) wrapper classes in C++ for your C++ library. – dtb Mar 18 '10 at 14:30