gpt4 book ai didi

c++ - 如何将 void 指针转换为函数指针

转载 作者:行者123 更新时间:2023-11-27 23:38:25 26 4
gpt4 key购买 nike

我正在尝试编写一个将附加一些函数指针的类。

这个指针将从这个类的另一个方法中调用。我将把函数指针存储在一个 void* vector 上,这样任何东西都可以放在一个 vector 上,而不是每种类型都有一个不同的 vector 。

我打算为我需要从类内部调用的任何不同函数声明不同的 AppendCallback 方法,例如:

void MyClass:AppendCallback(void (*Callback)())
{
_CallbackVector.push_back((void*)Callback);
_IdVector.push_back(VoidID);
}

void MyClass:AppendCallback(void (*Callback)(uint32_t));
void MyClass:AppendCallback(void (*MyOtherClass::Callback)());
void MyClass:AppendCallback(void (*MyOtherClass::Callback)(uint32_t));

将有第二个 vector ,它只包含标识符以了解 void* 指向什么,这也将在 AppendCallback 方法上分配。

如何将 void 指针再次转换为调用这些函数的函数指针?

也许是这样的?

void MyClass::Service(uint32_t x)
{
for(uint i = 0; i < _CallbackVector.size(); i++)
{
switch(_IdVector[i])
{
case VoidID: void(*_CallbackVector[i]()); break;
case Uint32ID: void(*_CallbackVector[i](x)); break;
}
}
}

编辑:

这是从 void* 转换为函数指针的正确方法吗?

最佳答案

That's not allowed in C++ :

Converting a void* to a function pointer directly is not allowed (should not compile using any of the casts) in C++98/03. It is conditionally supported in C++0x (an implementation may choose to define the behavior and if it does define it then it must do what the standard says it should do. A void*, as defined by the C++98/03 standard, was meant to point to objects and not to contain function pointers or member pointers.

And again :

You can't.

You can cast a data pointer to void* and then back to the same pointer type you have started with. std::function is not a pointer type, so the cast is statically invalid, and it's not the same thing you have started with. You have started with a .target of type void()() but it's not a data pointer, it's a function pointer, so casting it to void and back is implementation-defined.

在你的具体情况下,你可以尝试这样的事情:

class PointerToFunction {

};

template <typename Type>
class PointerToFunctionType : public PointerToFunction, std::function<Type> {
public:
using std::function<Type>::function; // I think this is the right syntax for this trick: https://softwareengineering.stackexchange.com/a/197901/342247


};

// Now, we can do this:

std::vector<PointerToType*> _CallbackVector;

基本上,我们使用类似于 how boost::any/std::any (since C++17) is implemented 的继承技巧存储任何 std::function在一个指针中。唯一的问题是知道如何将其转换回来。正确地执行此操作将取决于您希望如何将 void* 转换回开头(即,了解其类型),所以我将把这部分留给您。

关于c++ - 如何将 void 指针转换为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435515/

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