C API的设计:谁应该分配? [英] C API design: Who should allocate?
问题描述
什么是正确的/ preferred在一个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)隐藏的malloc
在 _init
和免费$ C $(C S) > S IN
_destroy
。
2) Hide malloc
s in _init
and free
s in _destroy
.
优点:更短的code,因为函数将被称为反正。完全不透明的结构。
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屋!