简体   繁体   中英

Using C++ struct in C

I have a C++ struct with methods inside:

struct S
{
   int a;
   int b;

   void foo(void)
   {
       ... 
   };
}

I have a userprogram, written in C . Is it possible to get a pointer to a S -struct and access the member a and b ?

You can access the members of a struct written in C++ from a C-program given you ensure that the C++ additions to the struct syntax are removed:

// header
struct S {
  int a, b;

#ifdef __cplusplus
  void foo(); 
#endif
};

// c-file:
#include "header.h"

void something(struct S* s)
{
  printf("%d, %d", s->a, s->b);
}

The memory layout of structs and classes in C++ is compatible with C for the C-parts of the language. As soon as you add a vtable (by adding virtual functions) to your struct it will no longer be compatible and you must use some other technique.

If these methods are not virtual then it is OK. You can even have common header for C/C++ with using of __cplusplus macro:

struct S
{
   int a;
   int b;

#ifdef __cplusplus
   void foo(void)
   {
       ... 
   }
#endif /* end section for C++ only */
};

Remember that name of this struct in C is struct S not just S .

How do you get an S if your program is written in C? My guess is that a most precise description is that your program is written in a mix of C and C++ and you want to access some members of a C++ struct in the C part.

Solution 1: modify your C part so that it is in the common subset of C and C++, compile the result as C++ and now you may gradually use whatever C++ feature you want. That's what lot of projects did in the past. The most well know recent one being GCC.

Solution 2: provide an extern "C" interface to S and use it in your C part.

#ifdef __cplusplus
extern "C" {
#endif
    struct S;
    int getA(S*);
    int getB(S*);
#ifdef __cplusplus
}
#endif

The part which provides the implementation of getA and getB must be compiled as C++, but will be callable from C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM