人们使用哪些技术/策略在C(不是C ++)构建的对象? [英] What techniques/strategies do people use for building objects in C (not C++)?

查看:131
本文介绍了人们使用哪些技术/策略在C(不是C ++)构建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特别感兴趣的对象意味着是从内C中使用,而不是形成间preTED语言的核心如蟒对象的实现。

I am especially interested in objects meant to be used from within C, as opposed to implementations of objects that form the core of interpreted languages such as python.

推荐答案

我倾向于做这样的事情:

I tend to do something like this:

struct foo_ops {
    void (*blah)(struct foo *, ...);
    void (*plugh)(struct foo *, ...);
};
struct foo {
    struct foo_ops *ops;
    /* data fields for foo go here */
};

使用这些结构定义,code foo的实施看起来是这样的:

With these structure definitions, the code implementing foo looks something like this:

static void plugh(struct foo *, ...) { ... }
static void blah(struct foo *, ...) { ... }

static struct foo_ops foo_ops = { blah, plugh };

struct foo *new_foo(...) {
   struct foo *foop = malloc(sizeof(*foop));
   foop->ops = &foo_ops;
   /* fill in rest of *foop */
   return foop;
}

然后,在code,使用富:

Then, in code that uses foo:

struct foo *foop = new_foo(...);
foop->ops->blah(foop, ...);
foop->ops->plugh(foop, ...);

这code可以与宏或内联函数,所以它看起来被收拾更多的C-像

This code can be tidied up with macros or inline functions so it looks more C-like

foo_blah(foop, ...);
foo_plugh(foop, ...);

但如果你坚持使用一个相当短的名字为行动现场,简单地写了原本显示的code不是特别详细。

although if you stick with a reasonably short name for the "ops" field, simply writing out the code shown originally isn't particularly verbose.

这技术是完全足够用C实现一个相对简单的基于对象的设计,但它确实的的处理更高级的要求,如明确重新presenting类和方法的继承。针对这一情况,你可能会需要像图形对象(如埃夫拉伊姆提到),但我建议要确保你真的需要更复杂的框架的额外功能。

This technique is entirely adequate for implementing a relatively simple object-based designs in C, but it does not handle more advanced requirements such as explicitly representing classes, and method inheritance. For those, you might need something like GObject (as EFraim mentioned), but I'd suggest making sure you really need the extra features of the more complex frameworks.

这篇关于人们使用哪些技术/策略在C(不是C ++)构建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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