Razer
Razer

Reputation: 8211

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 aand b?

Upvotes: 5

Views: 5030

Answers (3)

AProgrammer
AProgrammer

Reputation: 52284

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.

Upvotes: 2

mauve
mauve

Reputation: 2016

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.

Upvotes: 10

PiotrNycz
PiotrNycz

Reputation: 24412

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.

Upvotes: 3

Related Questions