gpt4 book ai didi

c++ - 在 C 中使用 C++ 结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:38 25 4
gpt4 key购买 nike

我有一个 C++ 结构,里面有方法:

struct S
{
int a;
int b;

void foo(void)
{
...
};
}

我有一个用 C 编写的用户程序。是否可以获取指向 S 结构的指针并访问成员 ab

最佳答案

您可以从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com