简体   繁体   English

C++ 指针转换帮助,void* 到 boolean

[英]c++ pointer casting help, void* to boolean

Im learning C++ at the moment, and am having some issues with casting pointers.我目前正在学习 C++,并且在转换指针时遇到了一些问题。 In the first place I am not sure that what I am trying to do is what I want to do..首先,我不确定我想做的是我想做的。

I am trying to take a function that can return the appropriate pointer to various method pointers based on string parameters, and to then use the method pointer.我正在尝试采用一个函数,该函数可以根据字符串参数返回指向各种方法指针的适当指针,然后使用该方法指针。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

typedef void* (*plugin_function)(void*);

static class Plugin
{
public:
    static bool doBoolStuff(){
        return true;// A Simple function that returns true
    }
};

void* getFunction(string pluginName, string functionName)
{
    if(pluginName =="Bool"){
        return &Plugin::doBoolStuff;
            //If the string is right it should return a method pointer.
            //I think that void* has the ability to point to anything, I am trying
            //to use that functionality to create a system where I am able to set 
            //some parameters and get the appropriate method pointer.
    }else{
        return NULL;
    }
}

int main(int argc, _TCHAR* argv[])
{
    void* pluginFunction;
    pluginFunction = getFunction("Bool","");

    if(pluginFunction == &Plugin::doBoolStuff)cout<<"CastSuccesful!"<<endl;

    //This section right here is where my code is breaking.
    //
    // IntelliSense: expression preceding parentheses of apparent call must have              
    //(pointer-to-) function type   
    //c:\Users\Walter\Dropbox\Inscription\MethodCasting\MethodCasting\MethodCasting.cpp 
    //MethodCasting

    cout << "Bool function ->"<< pluginFunction()<<endl;
    cout << "--------------------------------"<<endl;
    system("pause");

}

Any feedback would be helpful.任何反馈都会有所帮助。

Edit: Not true, sorry.编辑:不是真的,对不起。 As @Stephen Lin pointed out, I failed to read the static modifier... So while what you want doesn't work for non-static member functions, it usually does work for static members using reinterpret_cast (this behavior is implementation-defined):正如@Stephen Lin 指出的那样,我没有阅读static修饰符......所以虽然你想要的不适用于非静态成员函数,但它通常适用于使用reinterpret_cast静态成员(这种行为是实现定义的) :

class Plugin {
    public:
    static bool foo()
    {
        std::cout << "Foo called!" << std::endl;
        return true;
    }
};

void *get_func()
{
    return reinterpret_cast<void *>(&Plugin::foo);
}

int main()
{
    void *pluginFunction = get_func();
    (reinterpret_cast<bool (*)()>(pluginFunction))();
    return 0;
}

Original post:原帖:


You can't.你不能。 According to this article :根据这篇文章

However, there is no way to cast the void * back to a member function pointer that you could actually use.但是,无法将void *回您可以实际使用的成员函数指针。

I've tried it myself.我自己试过了。 Actually, all of static_cast , reinterpret_cast and even old C-style casts refused to work - neither with void * , nor with bool (*)() (yes, I've even tried to cast from a non-member function pointer type to a member function type)...实际上,所有static_castreinterpret_cast甚至旧的 C 风格的强制转换都拒绝工作——无论是void *还是bool (*)() (是的,我什至试图从非成员函数指针类型转换为成员函数类型)...

Sorry, C++ doesn't seem to allow us to do this.抱歉,C++ 似乎不允许我们这样做。

It depends on your implementation, if you can do this.这取决于你的实现,如果你能做到这一点。 In portable C++ you can't.在便携式 C++ 中,你不能。 And even if you can, you need explicit casts (in this case reinterpret_cast<> ) to convert between different pointer types.即使可以,您也需要显式转换(在本例中为reinterpret_cast<> )以在不同的指针类型之间进行转换。

Note that this does not extend to real "method" pointers, that is to non-static member function pointers.请注意,这不会扩展到真正的“方法”指针,即非静态成员函数指针。 You cannot convert between member function pointers and either object pointers or ordinary function pointers.您不能在成员函数指针与对象指针或普通函数指针之间进行转换。 The approach I present at the end can be used, if you only have non-static member function pointers.如果您只有非静态成员函数指针,则可以使用我最后介绍的方法。

Portably reinterpret_cast<> can freely convert between function pointer types and object pointer types - although any use of the result except conversion back to the original type is undefined in almost all cases.可移植地reinterpret_cast<>可以在函数指针类型和对象指针类型之间自由转换——尽管在几乎所有情况下,除了转换回原始类型之外,对结果的任何使用都是未定义的。

For conversions between object pointer types and function pointer types, the C++11 standard says (§5.2.10 [expr.reinterpret.cast]/8):对于对象指针类型和函数指针类型之间的转换,C++11 标准说 (§5.2.10 [expr.reinterpret.cast]/8):

Converting a function pointer to an object pointer type or vice versa is conditionally-supported.有条件地支持将函数指针转换为对象指针类型,反之亦然。 The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv- qualification, shall yield the original pointer value.这种转换的含义是实现定义的,除了如果实现支持双向转换,将一种类型的纯右值转换为另一种类型并返回,可能具有不同的 cv 限定,将产生原始指针值。

So, it depends on your implementation (and should be documented in its documentation), if casting a function pointer to a void * compiles and back compiles at all.因此,这取决于您的实现(并且应该在其文档中记录),如果将函数指针转换为void *编译并反向编译。 Alas, if it does, you should get the expected behavior.唉,如果是这样,你应该得到预期的行为。

In your code the casts are missing.在您的代码中,缺少演员表。 You need a cast to the generic type (in your case void* ) in getFunction and you need to cast back to the original type in order to call the function.您需要在getFunction转换为泛型类型(在您的情况下为void* ),并且您需要转换回原始类型以调用该函数。 So you will need to know the original type in main() :所以你需要知道main()的原始类型:

void* pluginFunction = getFunction("Bool","");
// ....
cout << "Bool function ->"<< (reinterpret_cast<bool (*)()>(pluginFunction))()<<endl;

A more portable solution would be to use an arbitrary function pointer type, for example void (*)() to pass plugin function pointers around, so that you have:更便携的解决方案是使用任意函数指针类型,例如void (*)()来传递插件函数指针,以便您:

typedef void (*any_func_ptr)();

// If you wanted to use this for non-static member functions, you could do
//   struct AnyClass;
//   typedef void (AnyClass::*any_memfun_ptr)();

any_func_ptr getFunction(string pluginName, string functionName)
{
    if(pluginName =="Bool"){
        return reinterpret_cast<any_func_ptr>(&Plugin::doBoolStuff);
    }else{
        return NULL;
    }
}

int main(int argc, char* argv[])
{
    any_func_ptr pluginFunction = getFunction("Bool","");

    if(reinterpret_cast<bool (*)()>(pluginFunction) == 
         &Plugin::doBoolStuff)
             cout<<"CastSuccesful!"<<endl;

    cout << "Bool function ->"<< (reinterpret_cast<bool (*)()>(pluginFunction))()<<endl;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM