【问题标题】:Setting a calling convention for std::function为 std::function 设置调用约定
【发布时间】:2013-01-28 02:27:04
【问题描述】:

我对使用 std 很陌生,我目前正在尝试调用一个以 std::function 作为参数的函数。类似于以下内容:

在一个库中的 .h 文件中:

typedef bool t (/*Params*/);

void __stdcall Foo(std::function<t> &function) {m_function = function;}

std::function<t> m_function;

我导入了 lib 并尝试在另一个 cpp 文件中使用 Foo:

bool Implementation (/*Params*/)
{
   // Implementation
}

void Bar()
{
    Foo(std::function<t> (Implementation));
}

由于调用约定,我在为 x86(但不是 x64)编译时遇到链接器错误(LNK2019):

Unresolved External Symbol __stdcall Foo (class std::tr1::function<bool __cdecl(/*Params*/) const&)

据此,我了解到我需要将“t”和实现标记为 __stdcall,但这样做会导致其他编译失败。我还应该注意在同一个库中构建时正确编译的代码。有没有办法将调用约定与 std::function 相关联?

【问题讨论】:

  • 考虑到您说 64 位版本有效,首先检查您链接的库版本是否正确(32 位)。
  • 库已正确链接(并且正在正确解析其他函数)。我认为这个问题更多地与 x64 有一个更简单的调用约定故事有关。
  • 关于正确导出的函数还有一点需要注意的是,当我尝试将调用约定添加到我的类型 def(或在 std ::function 我得到一个功能错误。
  • 错误告诉你没有Foo的定义,只是头文件中的一个声明。您需要在某处(在您的库中?)为 Foo 定义,并且您需要链接到它。
  • 我意识到我上面的代码有点误导。我实际上确实在标题中有 Foo 的定义。 Foo 所做的只是设置一个成员变量。我会在上面纠正这个。

标签: c++ stl calling-convention


【解决方案1】:

试试:

void Foo(const std::function<bool()> &func)
{
  func();
}

bool Implementation (/*Params*/)
{
  cout << "Implementation"<<endl;
  return true;
}

void Bar()
{
    Foo(std::function<bool()>(&Implementation));
}

int main()
{
  Bar();
  return 0;
}

【讨论】:

  • 我尝试了您的一些建议(删除了 typedef 并通过了 &implementation 而不是 implementation),我最终得到了同样的错误。我还尝试显式地为 stdcall 创建一个指针并传递它,它会继续寻找 cdecl。接下来我将尝试转储 lib 并查看它导出函数的内容。
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多