外部Lambda函数
Extern Lambda Function
如何将以下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;
};
但你可能会因为有了一个功能而过得更好。但我想你有自己的理由。
相关文章:
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 在构造函数中使用 lambda 的 C++ 类
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++:Lambda 函数指针转换的用例是什么?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- std::映射服装比较函数和函数/lambda错误
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 将匿名函数(lambda)保存为函数类型变量
- 如何编写将自身作为回调传递的匿名函数/lambda