我有一个 C++
结构,里面有方法:
struct S
{
int a;
int b;
void foo(void)
{
...
};
}
我有一个用 C
编写的用户程序。是否可以获取指向 S
结构的指针并访问成员 a
和 b
?
最佳答案
您可以从 C 程序访问用 C++ 编写的 struct
的成员,前提是您确保删除了对结构语法的 C++ 添加:
// 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);
}
C++ 中结构和类的内存布局与 C 语言的 C 部分兼容。一旦您向结构中添加 vtable(通过添加虚函数),它将不再兼容,您必须使用其他一些技术。
关于c++ - 在 C 中使用 C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13000347/