使用 SWIG 通过 C 创建面向对象的 API
我正在使用 SWIG 为 C 库创建包装器。 C 库接口具有到面向对象的 API(我想以目标语言公开)的自然映射,但是直接使用 SWIG 来生成包装器将在目标语言中生成一个对象,其中包含所有C 库的接口。
我看到几个选项:
- 创建 C 库的 C++ 接口,然后用 SWIG 包装 C++
- 在每种目标语言中构建自定义类,在内部使用简单的非 OO SWIG 输出
我更喜欢要点 2,但我的问题是,这是一个好的方法吗?它很有吸引力,因为我希望完全控制目标语言的界面,同时尽量减少对高级 SWIG 功能的依赖。
I am using SWIG to create wrappers for a C library. The C library interface has a natural mapping to an object-oriented API (which I'd like to expose in the target language), but a straightforward usage of SWIG to produce wrappers will generate a single object in the target language with all of the interfaces of the C library.
I see a few options:
- Create a C++ interface to the C library, then wrap C++ with SWIG
- Build a custom classes in each target language that use the simple, non-OO SWIG output internally
I'd prefer bullet point 2, but my question is, is this an OK approach? It is attractive because I'd like to have full control over the interface in the target language with minimal amount of reliance on advanced SWIG features.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也更喜欢选项 2(“在每种目标语言中构建一个在内部使用简单的非 OO SWIG 输出的自定义类”)。
我的理由是:
你必须保持“更少的代码”。这
复杂的部分是C库+SWIG
包装纸,所以最好保留
尽可能小。创造
另一个 C++ 包装会让这个变得复杂
部分很多。
通常更容易
创建接口类
Python(或 Java?),只是因为它是
更高层次的抽象。
您可以应用适配器模式,它非常适合这种情况。
http://en.wikipedia.org/wiki/Adapter_pattern
I do also prefer option 2 ("Build a custom classes in each target language that use the simple, non-OO SWIG output internally").
My reasons are:
You have to mantain "less code". The
complex part is the C library + SWIG
wrappers, so the better is to keep
that as small as possible. Creating
another C++ wrap would complicate this
part a lot.
It is normally easier to
create the interface classes in
Python (or Java?), just because it is of a
higher level of abstraction.
You can apply the adapter pattern, which fits very well to this case.
http://en.wikipedia.org/wiki/Adapter_pattern
您看过 ctypes 和/或 cython?这两个选项都应该比使用 SWIG 简单得多;此外,ctypes 位于标准库中,在 python 版本升级时不需要重新编译(我认为它也可以跨平台工作)。
have you had a look at ctypes and / or cython? both options should be much simpler than using SWIG; moreover ctypes is in the standard library and it will not necessitate recompilation on python version upgrade (and i think it will work across platforms, too).