c ++指向重载函数的指针

时间:2013-07-25 08:23:34

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

我正在尝试使用boost :: python公开重载函数。 函数原型是:

#define FMS_lvl2_DLL_API __declspec(dllexport)
void FMS_lvl2_DLL_API write(const char *key, const char* data);
void FMS_lvl2_DLL_API write(string& key, const char* data);
void FMS_lvl2_DLL_API write(int key, const char *data);

我看到了这个答案:How do I specify a pointer to an overloaded function?
这样做:

BOOST_PYTHON_MODULE(python_bridge)
{
    class_<FMS_logic::logical_file, boost::noncopyable>("logical_file")
        .def("write", static_cast<void (*)(const char *, const char *)>( &FMS_logic::logical_file::write))
    ;
}

导致以下错误:

error C2440: 'static_cast' : cannot convert from 'overloaded-function' to 'void (__cdecl *)(const char *,const char *)'
      None of the functions with this name in scope match the target type

尝试以下方法:

void (*f)(const char *, const char *) = &FMS_logic::logical_file::write;

结果:

error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'void (__cdecl *)(const char *,const char *)'
          None of the functions with this name in scope match the target type

有什么问题以及如何解决?

修改 我忘了提几件事:

  • 我在win-7上使用vs2010 pro
  • write是logical_file的成员函数
  • FMS_logic是命名空间

2 个答案:

答案 0 :(得分:2)

如果写是纯函数,那么第二次尝试应该有效。从你的代码看,你似乎有一个成员函数。指向成员函数的指针很难看,你宁可使用函数对象。 但是:您必须发布整个代码,不清楚write是否是成员函数。

编辑:如果它是FMS_logic :: logical_file的成员函数,则语法为:

void (FMS_logic::logical_file::*f)(const char *, const char *) = &FMS_logic::logical_file::write;

这只适用于非静态成员函数,即如果函数是静态的,或者logical_file只是一个名称空间,就像你之前写的一样。

答案 1 :(得分:0)

您的代码不起作用,因为您的函数指针类型错误。您需要包含所有类型限定符(缺少DLL限定符),并且如Klemens所说,类名称。把它们放在一起,你的代码应该是

.def("write", static_cast<void FMS_lvl2_DLL_API
                            (FMS_logic::logical_file::*)(const char *, const char *)>
                         (&FMS_logic::logical_file::write))

感谢static_cast&lt;&gt;的提示,我遇到了和你一样的问题,只是没有dllexport,并且在添加static_cast后它起作用了: - )