gpt4 book ai didi

c - 隐藏结构成员

转载 作者:行者123 更新时间:2023-12-04 11:13:46 25 4
gpt4 key购买 nike

我知道以前可能有人问过这个问题,但我想用我的方法来解决这个问题并征求意见或可能是更好的方法。我有三个文件 a.h a.cmain.c 关于结构的函数原型(prototype)将在 a.h 中实现将在 a.c 中并从 main.c 调用结构将很简单它可以看起来像这样

struct ctx{
int x;
};

我希望 a.c 能够操纵结构的内容,但防止 main 知道里面有什么。所以我想将结构定义放在 a.c 而不是 a.h 中,并将 struct ctx; 作为原型(prototype)放在 a.h 中>这可行,但是 ctx 不能再分配到 main.c 中的堆栈上,因为编译器不知道要分配的大小。所以这引出了我的第一个问题:有没有办法在不知道结构定义的情况下将结构分配到堆栈。

所以我假设如果它在堆栈上是不可能的,那么也许我可以通过创建一个返回指针的简单 init 函数来将它传递到堆上。这确实有效,但会使过程过于复杂吗?

a.h

#ifndef a_h
#define a_h

#include <stdio.h>
#include <stdlib.h>
struct ctx;
int incctx(struct ctx* c);
struct ctx* initctx(void);
void destroyctx(struct ctx* c);
#endif /* a_h */

a.c

#include "a.h"
struct ctx{
int x;
};
int incctx(struct ctx* c){
return ++c->x;
}
struct ctx* initctx(){
struct ctx* c = malloc(sizeof(struct ctx));
c->x = 0;
return c;
}
void destroyctx(struct ctx* c){
free(c);
}

main.c

#include "a.h"

int main(){
struct ctx* c = initctx();
printf("%d\n",incctx(c));
printf("%d\n",incctx(c));
printf("%d\n",incctx(c));
destroyctx(c);
return 0;
}

这种设计解决了一些缺点的问题。1:如果我想让部分结构可见而不是整个结构怎么办?2:如果我希望结构定义可用于其他文件,例如 b.hb.c,我是否必须重新定义结构?你们有没有更简洁的设计?我知道有人说您可以在结构中放置一个 void* 而不是特定类型,然后将它们标记为任意名称,但我认为这不是一个可行的解决方案。

最佳答案

对于可见性问题,您可以以类似继承的方式使用两个结构。

首先,您拥有在头文件中定义的公共(public)结构以及您的 API 处理指向的指针:

struct ctx
{
// Public data
};

然后在源文件中创建一个私有(private)结构,其中公共(public)结构是第一个成员:

struct private_ctx
{
struct ctx ctx; // The public part of the structure

// Followed by private data
};

在 API 内部,您使用 private_ctx 结构,而使用您的 API 的代码将仅使用公共(public) ctx 结构。

像这样的嵌套结构类似于继承,private_ctx 结构是一个 ctx 结构。您可以创建一个 private_ctx 结构并返回指向它的指针,该指针适本地转换为 ctx 结构。

下面是一个关于如何创建结构的例子:

struct ctx *create_struct(void)
{
// Allocate the private structure, which contains the public structure
struct private_ctx *data = = malloc(sizeof *data);

// Return the public part of the structure
return (struct ctx *) data;
}

通过反向转换使用私有(private)数据同样容易:

void use_data(struct ctx *data)
{
struct private_ctx *private_data = (struct private_ctx *) data;

// Here the private data can be used...
}

关于c - 隐藏结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596168/

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