【问题标题】:Call c++ function pointer from c#从 c# 调用 c++ 函数指针
【发布时间】:2011-01-29 01:18:12
【问题描述】:

是否可以像这样调用 c(++) 静态函数指针(不是委托)

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

来自 c#?

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

我需要能够从 c# 回调到一些旧的 c++ 类。 C++ 是托管的,但这些类还不是 ref 类。

到目前为止,我不知道如何从 c# 调用 c++ 函数指针,这可能吗?

【问题讨论】:

标签: c# c++ function-pointers


【解决方案1】:

dtb 是对的。这是 Marshal.GetDelegateForFunctionPointer 的更详细示例。它应该适合你。

在 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));
}

在 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);
  }
}

【讨论】:

    【解决方案2】:

    看看Marshal.GetDelegateForFunctionPointer 方法。

    delegate void MyCppFunc(IntPtr someObject);
    
    MyCppFunc csharpfuncptr =
        (MyCppFunc)Marshal.GetDelegateForFunctionPointer(funcptr, typeof(MyCppFunc));
    
    csharpfuncptr(param);
    

    不过,正如 MSDN 文档所述,我不知道这是否真的适用于您的 C++ 方法:

    您不能将此方法与通过 C++ 获得的函数指针一起使用

    【讨论】:

    • 描述说:“你不能用这个方法和通过 C++ 获得的函数指针一起使用”——很遗憾,我的函数指针是一个 C++ 指针。
    • 那么你唯一的选择是,我猜,在 C++ 中为你的 C++ 库创建托管(引用)包装类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多