C API 设计:谁应该分配? [英] C API design: Who should allocate?
问题描述
在 C API 中分配内存的正确/首选方法是什么?
What is the proper/preferred way to allocate memory in a C API?
起初,我可以看到两个选项:
I can see, at first, two options:
1) 让调用者完成所有(外部)内存处理:
1) Let the caller do all the (outer) memory handling:
myStruct *s = malloc(sizeof(s));
myStruct_init(s);
myStruct_foo(s);
myStruct_destroy(s);
free(s);
_init
和 _destroy
函数是必要的,因为内部可能会分配更多的内存,并且必须在某处处理.
The _init
and _destroy
functions are necessary since some more memory may be allocated inside, and it must be handled somewhere.
这样做的缺点是比较长,但在某些情况下也可以消除 malloc(例如,它可以传递一个堆栈分配的结构:
This has the disadvantage of being longer, but also the malloc can be eliminated in some cases (e.g., it can be passed a stack-allocated struct:
int bar() {
myStruct s;
myStruct_init(&s);
myStruct_foo(&s);
myStruct_destroy(&s);
}
另外,调用者必须知道结构体的大小.
Also, it's necessary for the caller to know the size of the struct.
2) 隐藏 _init
中的 malloc
和 _destroy
中的 free
.
2) Hide malloc
s in _init
and free
s in _destroy
.
优点:代码更短,因为无论如何都会调用函数.完全不透明的结构.
Advantages: shorter code, since the functions are going to be called anyway. Completely opaque structures.
缺点:不能传递以不同方式分配的结构体.
Disadvantages: Can't be passed a struct allocated in a different way.
myStruct *s = myStruct_init();
myStruct_foo(s);
myStruct_destroy(foo);
我目前倾向于第一种情况;再说一次,我不知道 C API 设计.
I'm currently leaning for the first case; then again, I don't know about C API design.
推荐答案
我最喜欢的精心设计的 C API 示例是 GTK+ 使用您描述的方法 #2.
My favourite example of a well-design C API is GTK+ which uses method #2 that you describe.
虽然您的方法#1 的另一个优点不仅是您可以在堆栈上分配对象,而且您可以多次重用同一个实例.如果这不是一个常见的用例,那么#2 的简单性可能是一个优势.
Although another advantage of your method #1 is not just that you could allocate the object on the stack, but also that you could reuse the same instance multiple times. If that's not going to be a common use case, then the simplicity of #2 is probably an advantage.
当然,这只是我的意见:)
Of course, that's just my opinion :)
这篇关于C API 设计:谁应该分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!