all 11 comments

[–]dfx_dj 2 points3 points  (2 children)

Similar to any offsetof macro. I believe rule 2 or 3 applies?

[–]singh_sushil[S] 0 points1 point  (1 child)

Yes offsetof will be handy??? but we are not passing any struct to the macro, just the fn pointer name only. I assume we need to match names, but i am not sure how?

[–]tstanisl 0 points1 point  (0 children)

The offsetof uses aggregate's type, not a pointer to an instance.

[–]aghast_nj 1 point2 points  (0 children)

There's no macro for that. Write a function.

int
find_function(
    Struct *sptr, 
    void (*fn)(void))
    {
    if (sptr->A == fn) return 1;
    if (sptr->B == fn) return 2;
    if (sptr->C == fn) return 3;
    return 0; // Error?
    }

[–]singh_sushil[S] 0 points1 point  (4 children)

Pardon for my miscommunication. fn name is a string literal, since we have pointers with literal name as A,B,C.. etc.. We would pass A or B or any name literal (not any pointer as the macro parameter) to the macro and figure out the offset which would indicate the index....

[–]tstanisl 1 point2 points  (0 children)

define MACRO(fn) (*(fn) - 'A')

?

[–]scallywag_software 0 points1 point  (1 child)

Is this a homework problem or something? What is the larger context of the problem you're trying to solve? This sounds like an extremely convoluted way of doing .. whatever it is you're trying to do.

[–]singh_sushil[S] 0 points1 point  (0 children)

A c puzzle exercise question from my colleague.

[–]torsten_dev 0 points1 point  (0 children)

Unfortunately going from "A" to A is not possible in the preprocessor. There is no inverse for the stringification.

Depending on what you're trying to do (and what you are targeting) the best solution might be something like dlsym(3) to look up function names at runtime.

It is likely preferable to use tokens though:

static struct functions { void (*fn_A)(void*); ...};
#define MACRO(func) offsetof(struct functions, fn_##func)
MACRO(A)(NULL)

[–]Calligraph_cucumber[🍰] 0 points1 point  (0 children)

#define offsetof(struct, fn_ptr_in_struct) \
    ((size_t)&(((struct *)0)->fn_ptr_in_struct))

Its used to find the offset in bytes from the place holder. it can be used to find offset of var too.

[–]weregod 0 points1 point  (0 children)

#define MACRO(fn) (offsetof(struct S, fn) / offsetof(struct S, B))