Using C ++ struct in C

I have a C++ structure with methods inside:

 struct S { int a; int b; void foo(void) { ... }; } 

I have a user program written in C Is it possible to get a pointer to an S structure and access the elements a and b ?

+4
source share
3 answers

You can access struct elements written in C ++ from a C program if you make sure that the C ++ additions to the structure 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 structures and classes in C ++ is compatible with C for the C-parts of the language. Once you add vtable (adding virtual functions) to your structure, it will no longer be compatible, and you should use a different technique.

+7
source

If these methods are not virtual, then this is normal. You can even have a common header for C / C ++ using the __cplusplus macro:

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

Remember that the name of this structure in C is equal to struct S not only S

+3
source

How do you get S if your program is written in C? I assume that the most accurate description is that your program is written in combination with C and C ++, and you want to access some members of the C ++ structure in part C.

Solution 1: change your C part so that it is in a common subset of C and C ++, compile the result as C ++, and now you can gradually use any C ++ function you want. This is what has been done in the past. The most famous of the latter is GCC.

Solution 2: provide the ā€œCā€ front end for 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 that provides the implementation of getA and getB must be compiled as C ++, but will be called from C.

+2
source

Source: https://habr.com/ru/post/1441129/


All Articles