C++调用 C 函数与 C 结构指针参数
C++ call C function with C struct pointer parameter
如果我没记错的话。此代码应该有效。
#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 源代码(没有外部"C")。如何在不修改 C 部分的情况下使其按C++编译?
编辑:我修改了代码,以便它可以在 C 和 C++ 中实际复制和测试。
它用 C 编译(同时生成警告),因为类型滥用在 C 世界中更容易被接受。编译器通常允许违反标准。
在C++中,您需要reinterpret_cast
指针:
Init(reinterpret_cast<Base*>(&d));
或
Init((Base*)&d);
理想情况下,您需要将此指针滥用封装到最小的可维护函数或类套件中。
你的Derived
名字是误导性的。你不是从Base
中推导出Derived
,C 中的结构等价性并没有多大意义。它可以与 cast 一起使用,但您必须在没有任何编译器帮助的情况下保持这种等效性。当有一天你决定改变Base
定义时
typedef struct {
int a;
int c; /* New field */
} Base;
您必须修改所有"派生"定义。
在 C 中,派生通常通过嵌入来模拟:
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int a;
} Base;
typedef struct {
Base base;
} Derived;
void Init(Base* b) {
b->a = 1;
}
#ifdef __cplusplus
}
#endif
int main() {
Derived d;
Init(&d.base);
}
相关文章:
- 为函数定义符号不明确的指针参数
- 构造函数 (C++) 中的 char 指针参数存在问题
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么具有指针参数的成员函数需要指向指针的指针?
- 通过引用函数传递指针参数是什么意思?
- 从double到double*的指针参数
- void 函数中的指针参数返回不一致的值
- 无法向上转换指针到指针参数
- 将数组动态分配到具有指针参数的函数中
- 模板函数指针参数与构造函数参数
- 使用通用函数指针参数化函数模板的简洁方法
- 如何为C++字符串分配空指针参数?
- C++带有指针参数的函数
- 指针参数的默认值
- 将常量添加到函数模板指针参数
- 如何传递unique_ptr<T>代替原始*输出*指针参数?
- 不带星号的函数指针参数
- 功能指针参数参数转换为const
- 将指针参数传递给双指针参数
- 如何调试指针参数是否通过函数修改