C++动态链接库中的回调函数

Callback functions in C++ dynamic linked library

我有一个 C++ 动态链接库。我想要做的是在库中声明一个回调函数,并将其留给用户在使用该库的代码中定义。伪代码示例:

//in library
void userDefinedFunction();

void libraryFunction() {
    //do stuff
    userDefinedFunction();
    //do more stuff
}
//in user code
void userDefinedFunction() {
    //user-specific code
}

这在现代 C++ 中可行吗?

当然可以。您的库可以接受指向用户定义函数的函数指针或对用户提供的仿函数的引用。 void libraryFunction() 将仅使用它来调用用户函数。

您可以使用功能库中的 std::function。这是一个带有 lambda 表达式和函数的示例

#include <iostream>
#include <functional>

 std::function<int (int)> func;

int testfunc(int i)
{
    std::cout<<"testfunc function called "; 
    return i+7; 

}

void process()
{
    if (func)
        std::cout<<func(3)<<std::endl;
}
int main()
{
    process();
    func = [](int i) { 
        std::cout<<"Lambda function called "; 
        return i+4; 
    };
    process();
    func = testfunc;
    process();
    return 0;
}