Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ struct in C

Tags:

c++

c

struct

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?

like image 414
Razer Avatar asked Dec 12 '22 21:12

Razer


1 Answers

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.

like image 186
mauve Avatar answered Dec 29 '22 20:12

mauve