【发布时间】:2022-01-07 19:53:58
【问题描述】:
我想为我编写的 C++ 库创建一个 C 包装器。
我找到的所有示例和 SO 的答案:
使用 void,typedef void myhdl_t
木马结构:struct mather{ void *obj; };
# .h
struct mather;
typedef struct mather mather_t;
# .cpp
struct mather{
void *obj;
};
mather_t *mather_create(int start){
mather_t *m;
CPPMather *obj;
m = (typeof(m))malloc(sizeof(*m));
obj = new CPPMather(start);
m->obj = obj;
return m;
}
从 C++ 基类派生结构
# .h
struct Foo;
#.cpp
struct Foo : public FooInternal {
using FooInternal::FooInternal;
};
struct Foo* foo_new() {
try {
return new Foo;
} catch(...) {
return nullptr;
}
}
我的情况:
我想要一个这样的分配 C 函数:
int alloc_function(struct Foo** foo){
if (foo==nullptr)
return -EFAULT; // The user gives nullptr
if (*foo!=nullptr)
return -EFAULT; // already allocated
// error: Incompatible pointer types assigning to 'struct Foo *' from 'Foo *'
*foo = new Foo;
// No error but Clang-Tidy: Do not use static_cast to downcast from a base to a derived class
*foo = static_cast<struct Foo*>(new Foo);
return 0;
}
我了解 Clang-Tidy 不是编译器错误,但我仍然希望以正确的方式进行操作。
- 编写 C 包装器的最佳实践是什么?有什么真实的例子吗?
【问题讨论】:
-
error: Incompatible pointer types assigning to 'struct Foo *' from 'Foo *'发布完整的minimal reproducible example。static_cast<struct Foo*>(new Foo);只是reinterpret_cast它。