DEV Community

Paul J. Lucas
Paul J. Lucas

Posted on Edited on

Pointers to Member in C

#c

Introduction

Suppose you have structures like this in C++:

struct loc {
  std::string path;
  unsigned    line, col;

  void print( std::ostream& ) const;
};

struct symbol {
  // ...
  loc dec_loc;  // Location of declaration.
  loc def_loc;  // Location of definition.
};
Enter fullscreen mode Exit fullscreen mode

and you want to iterate over a container of symbols and print one of their locations. Hence, for each symbol, you need a pointer to one of that symbol’s locations, not an ordinary pointer to symbol. Fortunately, C++ provides pointers to member so you can do something like:

void print_sym_locs( std::vector<symbol> const &syms,
                     loc symbol::*ploc ) {
  for ( auto const &sym : syms )
    (sym.*ploc).print( std::cout );
}

std::vector<symbol> syms;

void f() {
  // ...
  print_sym_locs( syms, &symbol::def_loc );
}
Enter fullscreen mode Exit fullscreen mode

The loc symbol::*ploc declares ploc as a pointer to any loc member of symbol. That is, given a particular symbol object, ploc can point to either dec_loc or def_loc. Hence the:

    (sym.*ploc).print( std::cout );
Enter fullscreen mode Exit fullscreen mode

means "call the print member function on whichever loc member ploc points to for sym." At a point of call, we pass the address of which location we want, here def_loc:

  print_sym_locs( syms, &symbol::def_loc );
Enter fullscreen mode Exit fullscreen mode

Behind the curtain, a pointer to member is really an offset, in this case from the start of a symbol’s address.

Pointers to member aren’t used all that often, but in cases like the above, they’re quite handy. C doesn’t have pointers to member explicitly, but you can get the same effect.

Pointers to Member in C

What C does have is the standard offsetof macro (defined in stddef.h). Assuming you have a typedef for struct symbol, you can do:

size_t offset = offsetof( symbol, def_loc );
Enter fullscreen mode Exit fullscreen mode

and offset will be the offset in bytes from the start of any symbol of its def_loc member. To reimplement the above in C, you’d do:

typedef struct loc loc;
typedef struct symbol symbol;

struct loc {
  char const *path;
  unsigned    line, col;
};

void loc_print( loc const *ploc, FILE *file ) {
  fprintf( file, "\"%s\":%u,%u", ploc->path, ploc->line, ploc->col );
}

void print_sym_locs( symbol const *syms, size_t n, size_t loc_off ) {
  for ( size_t i = 0; i < n; ++i ) {
    loc const *ploc = (loc const*)((char const*)&syms[i] + loc_off);
    loc_print( ploc, stdout );
  }
}

symbol const syms[] = {
  { { "a.h", 1, 2 }, { "b.h", 3, 4 } }
};

void f() {
  // ...
  print_sym_locs( syms, 1, offsetof( symbol, def_loc ) );
}
Enter fullscreen mode Exit fullscreen mode

Using offsetof, though a bit verbose, is fine. But the:

loc const *ploc = (loc const*)((char const*)&syms[i] + loc_off);
Enter fullscreen mode Exit fullscreen mode

is too verbose (not to mention ugly) even though all parts of it are needed:

  1. The &syms[i] is the address of the current symbol.
  2. The (char const*) is needed to cast the pointer to a character pointer in order to add loc_off bytes to it.
  3. The (loc const*) is needed to cast the (char const*) from the previous step back to a loc pointer.

It would be nice to hide all that ugliness in a macro. While we’re at it, it would also be nice to preserve const-ness, that is, given a const pointer, you get a const pointer back; likewise with a non-const pointer.

A Pointer to Member Macro

Here’s such a macro:

#define MEMBER_AT(OBJ_PTR,MBR_OFF) \
  TO_VOID_PTR_EXPR( TO_TYPE_PTR_EXPR( char, (OBJ_PTR) ) + (MBR_OFF) )
Enter fullscreen mode Exit fullscreen mode

where TO_TYPE_PTR_EXPR uses _Generic to cast OBJ_PTR to a char* preserving const-ness:

#define TO_TYPE_PTR_EXPR(TYPE,EXPR)     \
  _Generic( TO_VOID_PTR_EXPR(EXPR),     \
    void*       : (TYPE      *)(EXPR),  \
    void const* : (TYPE const*)(EXPR)   \
  )
Enter fullscreen mode Exit fullscreen mode

and TO_VOID_PTR_EXPR (that I previously wrote about in the _Generic article) is:

#define TO_VOID_PTR_EXPR(EXPR)    (1 ? (EXPR) : (void*)(EXPR))
Enter fullscreen mode Exit fullscreen mode

As a reminder, this pointless looking use of the ternary operator uses a particular quirk of it:

  • If either of the if-true or if-false expressions of ?: is void*, then the type of the result shall also be void* (plus const if either is const).

Given those macros, you can now instead write:

loc const *ploc = MEMBER_AT( &syms[i], loc_off );
Enter fullscreen mode Exit fullscreen mode

That’s a lot better. While it works just fine, a problem with it is that it’s not type-safe. You could pass the offset of any type of member, retrieve is as a different type, and the compiler wouldn’t complain.

Type-Safe Pointer-to-Member Macros

In C23 with typeof, we can do better. Instead of passing a size_t containing the offset that has no additional information about either the structure or member types, we can create a pointer-to-member type:

#define PTR_TO_MBR(ST,MT)  typeof( MT* (*)(ST*) )
Enter fullscreen mode Exit fullscreen mode

where ST is the structure type and MT is the member type. The type is actually a pointer-to-function taking ST* and returning MT*. Using a pointer-to-function allows a single type to encode both the structure and member types. A function can then be written like:

void print_sym_locs( symbol const *syms, size_t n,
                     PTR_TO_MBR(symbol, def_loc) ploc ) ) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

The next step is to implement a typed version of offsetof:

#define TYPED_OFFSETOF(ST,MBR_NAME)                         \
  ( (PTR_TO_MBR( ST, typeof_unqual( ((ST*)0)->MBR_NAME ) )) \
    (uintptr_t)offsetof( ST, MBR_NAME ) )
Enter fullscreen mode Exit fullscreen mode

The idea is to call offsetof, but then cast the result via a uintptr_t (a standard, unsigned integer guaranteed to be able to hold the value of a pointer) to a PTR_TO_MBR type.

  1. The ((ST*)0)->MBR_NAME is the trick that offsetof itself uses to get offset (since it’s relative to the memory address 0) of the member.
  2. typeof_unqual gets the type of that member without either const or volatile.
  3. Then that type is passed to PTR_TO_MBR as the member type, and that’s used to cast the uintptr_t to our pointer-to-member type.

Hence, at the point of call, replace offsetof with TYPED_OFFSETOF:

print_sym_locs( syms, 1, TYPED_OFFSETOF( symbol, def_loc ) );
Enter fullscreen mode Exit fullscreen mode

The last step is to implement TYPED_MEMBER_AT. Since it’s complicated, it helps to use a helper macro:

#define TYPED_MEMBER_AT(OBJ_PTR,MT,MBR_OFF)                     \
  TO_TYPE_PTR_EXPR( MT,                                         \
    TO_TYPE_PTR_EXPR( char, OBJ_PTR ) +                         \
      TMA_VALUE( typeof_unqual( *(OBJ_PTR) ), MT, (MBR_OFF) ) )

#define TMA_VALUE(ST,MT,MBR_OFF) \
  ((uintptr_t)(1 ? (MBR_OFF) : (PTR_TO_MBR( ST, MT ))0))
Enter fullscreen mode Exit fullscreen mode

The TYPED_MEMBER_AT macro is similar to MEMBER_AT except it:

  1. Replaces the TO_VOID_PTR_EXPR with TO_TYPE_PTR_EXPR with MT (the member type).
  2. Uses the TMA_VALUE helper to extract the pointer offset while ensuring that the type member types match.

Another quirk of the ternary operator is that, if both operands are pointers, they must be of compatible types. From the parameter declaration of print_sym_locs, loc_off is of type PTR_TO_MBR(symbol, def_loc) that is the type of MBR_OFF. Hence, the ?: compares that type to the *OBJ_PTR and MT types passed to TYPED_MEMBER_AT, and the code will compile only if both the structure and member types match. This prevents you passing the offset of member M1 of structure S1 and attempting to extract it as an unrelated member M2 of structure S2.

At the point of call, replace MEMBER_AT with TYPED_MEMBER_AT:

loc const *ploc = TYPED_MEMBER_AT( &syms[i], loc, loc_off );
Enter fullscreen mode Exit fullscreen mode

To be clear, all the type-checking happens at compile-time with zero run-time overhead cost.

Conclusion

As mentioned, pointers to member aren’t used all that often, but in cases like the above, they’re quite handy. Pointers to members in C++ are implemented behind the curtain pretty much as above in C, just with a concise syntax.

Top comments (0)