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?
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.
OS-programming. The kernel is implemented in C++. My userspace has only C runtime. I have some shared structs between file system and userspace, but these include C++ specific code.opendir: linux.die.net/man/3/opendir This returns a DIR* and exactly this DIR is implemented in C++ in the filesystem.DIR* doesn't need to be accessed directly in C. Therefore I can define DIR* as simple unsigned int pointer. For simpler structs, with no virtual methods, the solution from @mauve works.
aandb. I don't need access tofoo.S-pointer points aC++object. I want to access to this memory fromC.