c# - 从 c# 调用 c++ 函数指针

标签 c# c++ function-pointers

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

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

来自 c#?

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

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

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

最佳答案

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

关于c# - 从 c# 调用 c++ 函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470487/

相关文章:

c# - Asp.net 服务器应用程序正在本地主机上运行,​​但不在 Azure 中运行(未处理的异常渲染组件 : ExpectedJsonTokens)

c++ - uint8_t 转换 (cpp) 的段错误

c++ - 引用无效

c++ - C/C++中原始指针和函数指针支持的操作有哪些?

c# - 获取 "Operation not permitted on IsolatedStorageFileStream."错误

c# - 如何在同一解决方案中使用来自多个项目的 NLog

c++ - 使用指向图像数据的指针访问 R、G 和 B 像素值

c++ - C/C++ : A (*eval(A (*function)(B), B b))(){ ... } 可能吗? (可能是 C++11 之前的版本)

C# 从元数据中获取视频文件持续时间

c++ - 为什么 MinGW-w64 浮点精度取决于 winpthreads 版本?