从已声明的函数生成函数指针

时间:2016-02-05 23:14:40

标签: c++ function-pointers

我有一个声明为int __stdcall MyFunction(int param, int param);的函数,当名称作为参数传递时,我需要在宏或模板中获得一个指向函数的指针。

这在C ++中是可行的还是我必须自己重写函数签名?

5 个答案:

答案 0 :(得分:1)

您可以通过以下方式为函数指针(它衰减到的函数指针或由address-of运算符返回的函数)创建类型别名:

#include <iostream>

int MyFunction(int param, int param1)
{
    std::cout << param << " " << param1 << std::endl;
    return 0;
}

using Myfunction_ptr_t = std::decay<decltype(MyFunction)>::type;
// or using Myfunction_ptr_t = decltype(&MyFunction);
// or using Myfunction_ptr_t = decltype(MyFunction) *;

int main()
{
    Myfunction_ptr_t Myfunction_ptr = MyFunction;
    Myfunction_ptr(1, 2);
}

这个例子应该使用auto specifier(自C ++ 11以来):

auto Myfunction_ptr = MyFunction;

但这对无法推理的背景没有帮助。

答案 1 :(得分:1)

函数指针的行为与其他指针一样。它是指向某个实体的存储器地址(在这种情况下是功能代码)。您可以在某处保存这些指针,然后在任何方便的情况下获取它们。

例如,您可以创建std :: string vs fun的静态地图。指针对:

static std::map<std::string, PTR_TYPE> funMap;

之后保存指向此地图的指针并在需要时检索它们。

如果你还没有指针,可能你会谈论库中的导出函数。在这种情况下,请查看基于* nix的ldd或其他平台的somethig simialar。您将需要搜索运行时链接程序信息并按名称查找功能。

其实我不明白为什么你说你无法链接这些功能。以标准方式执行:包含带有此类声明的头文件。使用声明。 Linker将为您完成工作。只需为它提供一个具有这些功能的库的路径。它将动态链接到所需的功能。这就是你应该做的。如果您没有这样的库,则需要在运行时通过(再次)链接器的帮助在运行时搜索函数。

答案 2 :(得分:0)

您可以在下面定义typedef

typedef int (__stdcall *MYFUN)(int, int);

测试用例:

int main() {
  MYFUN f = MyFunction;
  f(2, 3);
}

或者,您可以使用std::function对象,如下所示:

std::function<decltype(MyFunction)> myfun;

测试用例:

std::function<decltype(MyFunction)> myfun = MyFunction;
myfun(4, 5);

Live Demo

答案 3 :(得分:0)

知道了。 #include <list> #include <unordered_map> class browser { public: void visit (const std::string& page) { auto location = locations.find(page); if (location != locations.end()) { pages.erase(location->second); } pages.push_front(page); locations[page] = pages.begin(); } private: using Pages = std::list<std::string>; using Locations = std::unordered_map<std::string, Pages::iterator>; Pages pages; Locations locations; }; 将完成这项工作。

答案 4 :(得分:0)

您可以使用decltypeauto,如下所示

decltype(&FunctionName) pointer = &FunctionName;

auto pointer = &FunctionName;

我避免在C ++ 11和C ++ 14中自己手动将函数指针转换为类型:)