gpt4 book ai didi

C++ 使用 C struct 指针参数调用 C 函数

转载 作者:行者123 更新时间:2023-11-30 00:44:47 24 4
gpt4 key购买 nike

如果我没记错的话。此代码应该有效。

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
int a;
} Base;

typedef struct {
int a;
} Derived;

void Init(Base* b) {
b->a = 1;
}
#ifdef __cplusplus
}
#endif


int main() {
Derived d;
Init(&d); // error can not convert argument 1 from 'Derived *' to 'Base *'
}

它编译为 C 源代码(没有 extern "C")。如何在不修改 C 部分的情况下将其编译为 C++?

编辑:我修改了代码,以便它可以在 C 和 C++ 中实际复制和测试。

最佳答案

它在 C 中编译(同时生成警告),因为类型滥用在 C 世界中更容易被接受。编译器允许违反标准是很常见的。

在 C++ 中,您需要reinterpret_cast 指针:

Init(reinterpret_cast<Base*>(&d)); 

Init((Base*)&d); 

理想情况下,您希望将这种指针滥用封装到最小的可维护函数或类套件中。

关于C++ 使用 C struct 指针参数调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46884405/

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