0

I came from C programming and have a question about the way to go to solve the following problem in C++.

I'm designing a header file to be used in C program which is supposed to have C++ implementation. It roughly looks as

lib.h

typedef struct some_opaque_struct_ some_opaque_struct;

#ifdef __cplusplus
extern "C" {
#endif

some_opaque_struct *init(int);

#ifdef __cplusplus
}
#endif

lib.cc

struct some_opaque_struct_ {
public:
   class ExternalLibraryClass slc;
}

extern "C" some_opaque_struct_* init(int rank){
    //some implementation in C++
}

In C it is possible to cast a pointer to initial member of a struct to the pointer to the struct. It is guaranteed by the Standard:

N2310/6.7.2.1

A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

Is it possible to cast class ExternalLibraryClass * to struct some_opaque_struct_ * in a conforming way and if so how to do it. AFAIK usage of C style cast is discouraged in C++.

Some Name
  • 8,555
  • 5
  • 27
  • 77
  • 1
    I suspect the most proper way to do this in C++ is to use inheritance/polymorphism. Since the need to cast to the initial member of a struct is a manner of polymorphism too (when you implement polymorphism in C, it is most often done by having the "base class" struct as initial member). So rather than casting to the initial member, you would have an abstract base class pointer, then cast that one to the appropriate inherited class. – Lundin Jun 12 '20 at 12:27
  • 1
    Answered in https://stackoverflow.com/questions/50383187/is-it-a-strict-aliasing-violation-to-alias-a-struct-as-its-first-member/50383349#50383349 ? – Language Lawyer Jun 12 '20 at 12:41
  • 1
    Or much better: https://stackoverflow.com/questions/57979009/is-it-possible-to-get-a-pointer-to-one-subobject-via-a-pointer-to-a-different-u/57979183#57979183 – Language Lawyer Jun 12 '20 at 12:44
  • @LanguageLawyer Yes, exactly the thing, thanks. The pointer-interconvertibility is what I wanted to learn. – Some Name Jun 12 '20 at 13:03

0 Answers0