c ++ / cli将(托pipe)委托传递给非托pipe代码

如何将托pipeC ++(C ++ / CLI)的函数指针传递给非托pipe方法? 我阅读了一些文章,比如MSDN上的这篇文章,但它描述了两个不同的程序集,而我只需要一个。

这是我的代码:

1)标题(MyInterop.ManagedCppLib.h):

#pragma once using namespace System; namespace MyInterop { namespace ManagedCppLib { public ref class MyManagedClass { public: void DoSomething(); }; }} 

2)CPP代码(MyInterop.ManagedCppLib.cpp)

 #include "stdafx.h" #include "MyInterop.ManagedCppLib.h" #pragma unmanaged void UnmanagedMethod(int a, int b, void (*sum)(const int)) { int result = a + b; sum(result); } #pragma managed void MyInterop::ManagedCppLib::MyManagedClass::DoSomething() { System::Console::WriteLine("hello from managed C++"); UnmanagedMethod(3, 7, /* ANY IDEA??? */); } 

我试图创build我的pipe理委托,然后我试图使用Marshal::GetFunctionPointerForDelegate方法,但我无法编译。

是的,你需要Marshal :: GetFunctionPointerForDelegate()。 你的代码段缺less你想要调用的托pipe函数,我只做了一个。 您还必须声明托pipe委托types并创build它的一个实例,然后才能获取函数指针。 这运作良好:

 #include "stdafx.h" using namespace System; using namespace System::Runtime::InteropServices; #pragma managed(push, off) typedef void (* UnmanagedSummer)(int arg); void UnmanagedMethod(int a, int b, UnmanagedSummer sum) { int result = a + b; sum(result); } #pragma managed(pop) ref class Test { delegate void ManagedSummer(int arg); public: static void Run() { Test^ t = gcnew Test(); ManagedSummer^ managed = gcnew ManagedSummer(t, &Sum); IntPtr stubPointer = Marshal::GetFunctionPointerForDelegate(managed); UnmanagedSummer functionPointer = static_cast<UnmanagedSummer>(stubPointer.ToPointer()); UnmanagedMethod(1, 2, functionPointer); GC::KeepAlive(managed); // Important: ensure stub can't be collected while native code is running System::Diagnostics::Debug::Assert(t->summed == 3); } void Sum(int arg) { summed += arg; } int summed; }; int main(array<System::String ^> ^args) { Test::Run(); return 0; }