Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

c++ - How to convert a function pointer to function name?

I now have an array of functions that have the same functionality,

func_pointer_t func_array[] = {func_1, func_2, func_3, ...};

I want to develop a program that traverses through all the array members and dumps the output to another .dat data file. The output should have the following format:

func_1 func_1_output
func_2 func_2_output
func_3 func_3_output
...

So my question is - when traversing through the array members, how could we let the program know which function name the function pointer is pointing to (e.g. func_array[0] is pointing to func_1)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no standard way of archiving what you seek. All possible solutions either involve system dependent ways to resolve function addresses to their names (and even that does not necessarily always work) or changing the func_array like so:

struct {
    func_pointer_t func;
    const char * name;
} func_array[] = {
    { func_1, "func_1" },
    { func_2, "func_2" },
    { func_3, "func_3" },
    ...
};

you can use a macro, to ease the job:

#define FUNC_DEF(func) { func, #func },

and then use it like this:

struct {
    func_pointer_t func;
    const char * name;
} func_array[] = {
    FUNC_DEF(func_1)
    FUNC_DEF(func_2)
    FUNC_DEF(func_3)
    ...
};

So, if this is an option for you, you got your solution. If not, you gonna have to tell, what system you're targeting.

More C++ish solutions exist - like the std::map solutions hinted to by Govind Parmar where you could iterate and take the key <-> value pair.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...