Marshal委托给std :: function

时间:2015-05-29 10:56:55

标签: .net c++-cli

可以这样做吗?

可以使用以下代码完成对C风格函数指针的编组:

GCHandle rahHandlle = GCHandle::Alloc(reAuthHandler);
IntPtr rahPtr = Marshal::GetFunctionPointerForDelegate(reAuthHandler);
auto rahUnman = static_cast<SomeFuncPtr>(rahPtr.ToPointer());

但是如何编组std :: function呢?如果可以的话。

1 个答案:

答案 0 :(得分:1)

在C ++ / CLI .NET代码中声明一个与本机std :: function中的参数匹配的函数指针 - 并将.NET委托的指针强制转换为此函数。

//C++ CLI
IntPtr rahPtr = Marshal::GetFunctionPointerForDelegate(reAuthHandler);

//Declare a function pointer which matches the parameters of your native C++ std::function
typedef void(__stdcall * ThisIsMyCppFunctionDeclaration)(long);

//Then cast your delegate pointer to the c++ function pointer (which
auto callbackFunctionCpp = static_cast<ThisIsMyCppFunctionDeclaration>(rahPtr.ToPointer());

//And then finally invoke your native C++ method which takes a std::function
DoWork(callbackFunctionCpp);

-

//C++ Native
void DoWork(std::function<void(long theLongValue)> callback){
    //Do something
    callback(123);
}
相关问题