外部Lambda函数

Extern Lambda Function

本文关键字:函数 Lambda 外部      更新时间:2024-09-22

如何将以下lambda函数从源文件外部化为头,以便在其他源文件中使用它?

const auto perform_checks = [&]()
{
const auto func =
GetFunctionPEB(static_cast<LPWSTR>(L"ntdll.dll"), "NtSetDebugFilterState");
auto* func_bytes = reinterpret_cast<BYTE*>(func);
if (is_hooked(func_bytes))
{
ProtectionThread();
}
};

也许这正是你想要的方向

#include <functional>
#include <iostream>
// In header file
extern std::function<void(void)> externedFunction;
// In c++ file
std::function<void(void)> externedFunction = [](){
std::string msg = "performing checks";
const auto perform_checks = [msg]()
{
std::cout << msg << std::endl;
};
return perform_checks;
}();

这是一个可疑的用例。但是请注意,我通过值捕获消息。如果您通过引用捕获,则无法返回lambda,因为您将捕获对堆栈变量的引用,并且最终会出现未定义的行为,这可能意味着您的应用程序会崩溃

或者你也可以这样做。

#include <functional>
#include <iostream>
// In header file
extern std::function<void(void)> externedFunction;

// In c++ file
static std::string msg = "performing checks";
std::function<void(void)> externedFunction = 
[&msg]()
{
std::cout << msg << std::endl;
};

但你可能会因为有了一个功能而过得更好。但我想你有自己的理由。