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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With