开发者

Can I extract function arguments from a function pointer?

Can I extract extra information (like number of arguments and their types) from a function pointer? If (most likely) not, what is the best way to allow a programmer to pass in a function pointer and the variable number of arguments EDIT: I meant that it should allow functions with different number of arguments that it takes while making sure that the programmer does not pass incorrect argument types.

What I want to do: Expose functions and its arguments to scripting language without having a programmer to type the arguments out manually (and therefore allowing mistakes to occur where the programmer passes the function pointer and the incorrect arguments that the function takes in).

A little more clarification: I should be able to output the function name and the argument types for documentation purposes.

----------------- SOLUTION -----------------

开发者_StackOverflow社区

James's answer is what I was looking for. Here is the code as it is a bit convoluted that should help anybody stuck in the same situation.

boost::function_traits<boost::remove_pointer
                         <BOOST_TYPEOF(&SomeFunction)>::type>::arg2_type);

If you require output, use RTTI (assuming you have RTTI enabled in compiler)

std::cout << typeid(boost::function_traits<boost::remove_pointer
    <BOOST_TYPEOF(&SomeFunction)>::type>::arg2_type).name() << std::endl;


You can get the arity, return type, and parameter types of a function using function_traits from the Boost.TypeTraits library.

To fully enable your described scenario of having what is effectively a variadic function that is type safe, you really need variadic templates, a new feature being added in C++0x and supported by some recently released compilers (e.g., Clang, gcc). If you need something more extensive, you will probably need to implement your own runtime type system.


I'm not entirely clear what you're after, but boost.function_types can tell you the return type, number of arguments, and argument types of a function pointer.


You may want to consider using the Boost::Function library and Boost::TypeTraits. I find Boost::Function makes function pointers easier to deal with and allows you to use function objects in a generic way (i.e. you are not constrained by the type of the function object which is a pain), which are all round much nicer than raw function pointers


You could probably convert doxygen xml output into the proper declarations/metadata for your scripting language. The information in this other question might get you started. Otherwise SWIG might help you, it's designed for generating cross-language wrappers, and can probably generate them compatible with your scripting language of choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜