【发布时间】:2020-07-06 22:12:24
【问题描述】:
我想用 C 创建一个 API。我的目标是实现抽象以访问和改变 API 中定义的 struct 变量。
API的头文件:
#ifndef API_H
#define API_H
struct s_accessor {
struct s* s_ptr;
};
void api_init_func(struct s_accessor *foo);
void api_mutate_func(struct s_accessor *foo, int x);
void api_print_func(struct s_accessor *foo);
#endif
API 的实现文件:
#include <stdio.h>
#include "api.h"
struct s {
int internal;
int other_stuff;
};
void api_init_func(struct s_accessor* foo) {
foo->s_ptr = NULL;
}
void api_print_func(struct s_accessor *foo)
{
printf("Value of member 'internal' = %d\n", foo->s_ptr->internal);
}
void api_mutate_func(struct s_accessor *foo, int x)
{
struct s bar;
foo->s_ptr = &bar;
foo->s_ptr->internal = x;
}
使用 API 的客户端程序:
#include <stdio.h>
#include "api.h"
int main()
{
struct s_accessor foo;
api_init_func(&foo); // set s_ptr to NULL
api_mutate_func(&foo, 123); // change value of member 'internal' of an instance of struct s
api_print_func(&foo); // print member of struct s
}
我对我的代码有以下疑问:
-
是否有直接(非骇客)的方法来隐藏我的 API 的实现?
-
这是为客户端创建抽象以使用我的 API 的正确方法吗?如果没有,我该如何改进以使其变得更好?
【问题讨论】:
-
如果你谈论抽象,你还需要谈论封装,当谈论封装时,结构应该只暴露在c文件中(不完整类型)
-
为什么要使用extern?在这种情况下,您根本不需要使用它。只需定义没有外部的函数签名
-
从方便的角度来看,使用这个东西时有一个
typedef可以跳过struct部分。 -
@Adam 感谢您的建议。我已经从头文件中删除了 extern
-
@tadman 感谢您的建议!
标签: c abstraction