C API设计:谁应该分配? [英] C API design: Who should allocate?

查看:219
本文介绍了C API设计:谁应该分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我可以首先看到两个选项:



1)让调用者执行所有的(外部)内存处理:

  myStruct * s =的malloc(的sizeof(S)); 
myStruct_init(s);

myStruct_foo(s);

myStruct_destroy(s);
免费;

_init _destroy 函数是必要的,因为可能会在里面分配一些更多的内存,并且必须在某处处理。



这具有更长的缺点,而且在某些情况下也可以消除malloc(例如,它可以传递一个堆栈分配的结构体:

  int bar (){
myStruct s;
myStruct_init(& s);

myStruct_foo(& s);

myStruct_destroy(& ;
}

此外,调用者需要知道结构体的大小。



2)在 _init 中隐藏 malloc code> $ _destroy



优点:因为这些功能将被打来。完全不透明的结构。



缺点:不能传递以不同方式分配的结构。

  myStruct * s = myStruct_init(); 

myStruct_foo(s);

myStruct_destroy(foo);

我正在倾斜第一种情况;再次,我不知道C API设计。

解决方案

我最喜欢的一个精心设计的C API的例子是<一个使用你所描述的方法#2的href =http://www.gtk.org/ =noreferrer> GTK + 。



虽然方法#1的另一个优点不仅仅是您可以在堆栈上分配对象,而且您可以多次重复使用相同的实例。如果这不是一个常见的用例,那么#2的简单性可能是一个优势。



当然,这只是我的意见:)


What is the proper/preferred way to allocate memory in a C API?

I can see, at first, two options:

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);

The _init and _destroy functions are necessary since some more memory may be allocated inside, and it must be handled somewhere.

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) Hide mallocs in _init and frees 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);

I'm currently leaning for the first case; then again, I don't know about C API design.

解决方案

My favourite example of a well-design C API is GTK+ which uses method #2 that you describe.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆