外部 Lambda 函数

问题描述

如何将以下 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;

}();

这是一个可疑的用例。但是请注意,我按值捕获了 msg。如果您通过引用捕获,则无法返回 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;
    };
   

但是您可能只使用一个函数会更好。但我想你有你的理由。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...