2015-05-29 64 views
1

這可以做到嗎?元帥代表std :: function

編組到C風格的函數指針可以用下面的代碼來完成:

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

但是,如何將一個元帥到一個std ::功能?如果可以做到的話。

回答

0

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