您如何声明外部"C"功能指针 [英] How do you declare an extern "C" function pointer

查看:96
本文介绍了您如何声明外部"C"功能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码:

#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

所以出现此错误是因为math中的'log'是extern"C"

So this error is because 'log' is extern "C"'d in math.h

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

I was wondering how to declare my function pointer argument in foo() so it handles extern "C"'d functions.

推荐答案

您可以尝试改为包含cmath,并使用static_cast<double(*)(double)>(std::log)(解决double重载所需的强制转换).

You can try including cmath instead, and using static_cast<double(*)(double)>(std::log) (cast necessary to resolve to the double overload).

否则,您将功能限制为extern C个功能.就像

Otherwise, you will limit your function to extern C functions. This would work like

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

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

另一种方法是将foo用作函子

Another way is to make foo a functor

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

然后,您可以将foo()传递给boost::bind,并且由于它是模板化的,因此它将接受任何链接.它也将与函数对象一起使用,不仅与函数指针一起使用.

Then you can pass foo() to boost::bind, and because it's templated, it will accept any linkage. It will also work with function objects, not only with function pointers.

这篇关于您如何声明外部"C"功能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆