构造Python绑定到C或c++库的最快方法是什么?

(如果这很重要的话,我使用的是Windows。)


当前回答

Cython绝对是最好的选择,除非您希望编写Java包装器,在这种情况下,SWIG可能更可取。

我建议使用runcython命令行实用工具,它使使用Cython的过程极其简单。如果你需要向c++传递结构化数据,可以看看谷歌的protobuf库,它非常方便。

以下是我使用这两种工具的一个最小示例:

https://github.com/nicodjimenez/python2cpp

希望这能成为一个有用的起点。

其他回答

Cython绝对是最好的选择,除非您希望编写Java包装器,在这种情况下,SWIG可能更可取。

我建议使用runcython命令行实用工具,它使使用Cython的过程极其简单。如果你需要向c++传递结构化数据,可以看看谷歌的protobuf库,它非常方便。

以下是我使用这两种工具的一个最小示例:

https://github.com/nicodjimenez/python2cpp

希望这能成为一个有用的起点。

最快的方法是使用SWIG。

来自SWIG教程的例子:

/* File : example.c */
int fact(int n) {
    if (n <= 1) return 1;
    else return n*fact(n-1);
}

接口文件:

/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern int fact(int n);
%}

extern int fact(int n);

在Unix上构建Python模块:

swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so

用法:

>>> import example
>>> example.fact(5)
120

注意,你必须有python-dev。此外,在某些系统中,python头文件将位于/usr/include/python2.7中,这取决于您安装它的方式。

来自教程:

SWIG是一个相当完整的c++编译器,几乎支持所有语言特性。这包括预处理、指针、类、继承,甚至c++模板。SWIG还可以用于用目标语言将结构和类打包为代理类——以非常自然的方式公开底层功能。

问题是如何从Python中调用C函数,如果我理解正确的话。那么最好的选择是c类型(顺便说一句,可移植到所有Python变体)。

>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19

关于详细的指南,你可以参考我的博客文章。

我认为cffi可以作为python的一个选项。

目标是从Python调用C代码。你应该能够这样做 不学习第三种语言:每一种选择都需要你学习 学习他们自己的语言(Cython, SWIG)或API (ctypes)。所以我们尝试了 假设你懂Python和C语言,尽量减少多余的 你需要学习的API。

http://cffi.readthedocs.org/en/release-0.7/

你应该看看Boost.Python。以下是他们网站上的简短介绍:

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).