gpt4 book ai didi

c++ - 存储指向成员函数的指针

转载 作者:行者123 更新时间:2023-11-28 01:12:04 25 4
gpt4 key购买 nike

我正在包装一个现有的 C API,以使其更易于在我的 VS2008 C++ 程序中使用。 C API 需要一个包含函数指针的“TABLE_ENTRY”结构数组,如下面的代码所示。

但是,我很难在函数指针中存储指向成员函数的指针。谁能指出我可能做错了什么?

谢谢,保罗H

我的代码基本上是这样的:

struct TABLE_ENTRY; // forward decl

typedef int (WINAPI *MYPROC )(DWORD msg, TABLE_ENTRY* entry);

struct TABLE_ENTRY {
const char* description;
DWORD value;
MYPROC callback;
};

class MyClass
{
public:
MyClass() : description( "Some Description" ),
some_value( 1 )
{
};

int MyProc( DWORD msg, TABLE_ENTRY* my_entry )
{
return 0;
};

TABLE_ENTRY* operator*()
{
entry_.description = description.c_str();
entry_.value = some_value;
// error C2440: '=' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'MYPROC'
entry_.callback = boost::bind< int >( &MyClass::MyProc, this );
return &entry_;
};

TABLE_ENTRY entry_;
std::string description;
DWORD some_value;
};

class MyClassCollection
{
public:
TABLE_ENTRY* GetTable()
{
// is this okay or is it Evil & wrong?
return ( &collection_.front() )->operator*();
};

void Add( MyClass& my_class )
{
collection_.push_back( my_class );
}
private:
std::vector< MyClass > collection_;
};

int _tmain( int argc, _TCHAR* argv[] )
{
MyClass class1;
MyClass class2;

MyClassCollection collection;
collection.Add( class1 );
collection.Add( class2 );

TABLE_ENTRY* table = collection.GetTable();
TABLE_ENTRY entry1 = table[ 0 ]; // should be class1's table
TABLE_ENTRY entry2 = table[ 1 ]; // should be class2's table

return 0;
}

最佳答案

boost::bind 创建一个 functor,即实现 operator() 的类的实例.这不能与普通 C 函数指针互换。

关于c++ - 存储指向成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2366690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com