【问题标题】:How do you declare an extern "C" function pointer你如何声明一个外部“C”函数指针
【发布时间】:2010-11-20 07:48:02
【问题描述】:

所以我有这个代码:

#include "boost_bind.h"
#include <math.h>
#include <vector>
#include <algorithm>

double foo(double num, double (*func)(double)) {
  return 65.4;
}

int main(int argc, char** argv) {
  std::vector<double> vec;
  vec.push_back(5.0);
  vec.push_back(6.0);
  std::transform(vec.begin(), vec.end(), vec.begin(), boost::bind(foo, _1, log));
}

并收到此错误:

        return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
.............................................................^
%CXX-E-INCOMPATIBLEPRM, argument of type "double (* __ptr64 )(double) C" is
          incompatible with parameter of type "double (* __ptr64 )(double)"
          detected during:
            instantiation of ...5 pages of boost

所以这个错误是因为'log'在 math.h 中是 extern "C"'d

我想知道如何在 foo() 中声明我的函数指针参数,以便它处理外部“C”函数。

【问题讨论】:

  • 并不是说它回答了你的问题,但这种特殊情况不需要boost::bindstd::bind2nd 可以很好地完成这项工作。

标签: c++ function-pointers boost-bind


【解决方案1】:

您可以尝试包含cmath,并使用static_cast&lt;double(*)(double)&gt;(std::log)(需要强制转换以解决double 重载问题)。

否则,您会将函数限制为 extern C 函数。这会像

extern "C" typedef double (*ExtCFuncPtr)(double);

double foo(double num, ExtCFuncPtr func) {
  return 65.4;
}

另一种方法是使foo 成为仿函数

struct foo {
  typedef double result_type;
  template<typename FuncPtr>
  double operator()(double num, FuncPtr f) const {
    return 65.4;
  }
};

然后你可以将foo() 传递给boost::bind,因为它是模板化的,它会接受任何链接。它也适用于函数对象,而不仅仅是函数指针。

【讨论】:

  • 太棒了,我尝试了仿函数,但我没想过使用模板来修复所有类型。谢谢
【解决方案2】:

尝试使用 typedef:

extern "C" {
  typedef double (*CDoubleFunc)(double);
}

double foo(double num, CDoubleFunc func) {
  return 65.4;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2011-01-17
    • 2010-11-11
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多