【发布时间】:2023-03-03 03:34:01
【问题描述】:
我有 C/C++ 混合代码并希望传递一个包含对类的引用的结构。因此,我不能在 C++ 组件的头文件中声明这个结构(因为类是在 C++ 组件的源文件中定义的),而只能在源文件中声明。然而,C 中的主脚本必须以某种方式引用该结构,因此我将其 typedef 为 void*。但是正因为如此,我不能将句柄类型取消引用回结构。无法在源文件中重新定义句柄指针。我该如何解决这个问题?
header_with_obj.hpp
class A {
int a;
};
header.hpp
typedef void* config_handle_t;
source.cpp
#include "header.hpp"
#include "header_with_obj.hpp"
typedef struct {
A* ptr;
int some_other;
} config_t;
// typedef config_t* config_handle_t <-- error: conflicting declaration 'typedef struct config_t* config_handle_t '
int foo(void* arg)
{
config_handle_t handle = (config_handle_t) arg;
handle->A.a = 4; // <-- error: 'config_handle_t' {aka 'void*'} is not a pointer-to-object type
}
main.c
#include "header.hpp"
int main()
{
// we get that void* from somewhere and pass it in
foo(arg);
}
【问题讨论】:
-
你可以在没有任何转换的情况下做到这一点:把它放在
header.hpp:typedef struct config_t* config_handle_t;指向不完整类型的指针在 C 和 C++ 中都是有效的。并且您保留了类型安全性(有人不会意外传递int*)。 -
怎么样?我得到
error: unknown type name 'config_t' typedef config_t* config_handle_t;这是有道理的,因为 struct config_t 的声明在源文件中。 -
@glades 你写的是 config_t 而不是 struct config_t。此外,您还必须将结构声明为
struct config_t {...};而不是typedef struct {...} config_t;,因为在第二个结构中,该结构在技术上没有名称。 -
@RaymondChen 这是正确答案:您应该将其设为答案而不是评论。
-
@user253751:谢谢你现在的工作!多么微妙的区别,但我一直想知道 typedef 和 struct 实际上的区别是什么。如果我没记错的话,我想我现在必须将一些 malloc(sizeof(config_t)) 更改为 malloc (sizeof(struct config_t))?
标签: c++ c class typedef void-pointers