Python C++ 扩展

Posted by Liang Yulai on November 19, 2018

需求

1
2
* Python 模块编译为 so 文件
* Python 调用该 so 文件(C 也可以调用该 so 文件)

准备工作:安装 Cpython

1
pip install python-dev cpthon

创建 Cpython 文件: hello.pyx

1
2
3
4
5
6
kirin@kawagarbo:~/workspace/test$ tree
.
├── hello.pyx
├── setup.py
└── test.py

hello.pyx

1
2
3
4
5
6
7
class ctest:

    def print_hello(self):
        print "hello"

    def print_your_name(self, name):
        print name

setup.py

1
2
3
4
5
6
from distutils.core import setup
from Cython.Build import cythonize

setup(
        ext_modules = cythonize("hello.pyx")
)

test.py

1
2
3
4
5
6
7
8
9
#! /usr/bin/python2
from hello import ctest # import hello.so

def main(name):
    ctest().print_hello()
    ctest().print_your_name(name)

if __name__ == "__main__":
    main("Alex")

编译 pyx 文件为 so 文件

1
$ python setup.py build_ext --inplace

编译结果

1
2
3
4
5
6
7
8
9
10
kirin@kawagarbo:~/workspace/test$ tree
.
├── build
│   └── temp.linux-x86_64-2.7
│       └── hello.o
├── hello.c
├── hello.pyx
├── hello.so
├── setup.py
└── test.py

测试一下

1
2
3
kirin@kawagarbo:~/workspace/test$ ./test.py
hello
Alex

##

Cython Cython@Github Cython by Kurt W. Smith Cython examples