简体   繁体   English

使用SWIG在C上创建面向对象的API

[英]Creating an object-oriented API over C using SWIG

I am using SWIG to create wrappers for a C library. 我正在使用SWIG为C库创建包装器。 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. C库接口具有到面向对象API的自然映射(我想用目标语言公开),但是直接使用SWIG来生成包装器将生成目标语言中的单个对象,所有这些都是C库的接口。

I see a few options: 我看到几个选项:

  • Create a C++ interface to the C library, then wrap C++ with SWIG 创建C库的C ++接口,然后使用SWIG包装C ++
  • Build a custom classes in each target language that use the simple, non-OO SWIG output internally 在内部使用简单的非OO SWIG输出的每种目标语言中构建自定义类

I'd prefer bullet point 2, but my question is, is this an OK approach? 我更喜欢第2点,但我的问题是,这是一个好的方法吗? 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. 它很有吸引力,因为我希望能够完全控制目标语言中的界面,同时最大程度地依赖于高级SWIG功能。

I do also prefer option 2 ("Build a custom classes in each target language that use the simple, non-OO SWIG output internally"). 我也更喜欢选项2(“在内部使用简单的非OO SWIG输出的每种目标语言中构建自定义类”)。

My reasons are: 我的理由是:

  1. 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. 复杂的部分是C库+ SWIG包装器,所以最好保持尽可能小。 Creating another C++ wrap would complicate this part a lot. 创建另一个C ++包装会使这部分复杂化很多。

  2. It is normally easier to create the interface classes in Python (or Java?), just because it is of a higher level of abstraction. 在Python(或Java?)中创建接口类通常更容易,因为它具有更高的抽象级别。

  3. You can apply the adapter pattern, which fits very well to this case. 您可以应用适配器模式,这非常适合这种情况。 http://en.wikipedia.org/wiki/Adapter_pattern http://en.wikipedia.org/wiki/Adapter_pattern

have you had a look at ctypes and / or cython ? 你看过ctypes和/或cython吗? both options should be much simpler than using SWIG; 这两个选项应该比使用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). 而且ctypes在标准库中,它不需要在python版本升级时重新编译(我认为它也可以跨平台工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM