Skip to content

Commit b8cf7ca

Browse files
committed
0.0.1 C/C++ 拓展 Cpython 的详细文档
1 parent 26273cc commit b8cf7ca

File tree

1 file changed

+97
-1
lines changed

1 file changed

+97
-1
lines changed

README.md

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,100 @@
88

99
3、用 C/C++ 实现的功能支持像原生 Python 模块一样的导入
1010

11-
---
11+
---
12+
13+
## C/C++ 拓展的原理
14+
15+
Python 的优势在于语法简洁,在一些特定的情况下 Python 的执行效率达不到业务的要求,我们可以通过更加低层的语言(C/C++)来实现这一部分逻辑,进而解决性能问题。就我个人的经历而言 99.9% 的情况下可能通过优化算法来解决。
16+
17+
要想实例用 C/C++ 来拓展 python 总来看分 3 步走
18+
19+
1、用 C/C++ 来实现你的业务逻辑
20+
21+
2、给你的 C/C++ 代码增加一段翻译代码,这个 Python 解释器就能理解了,详细的可以看官方的 [extending](https://docs.python.org/3.8/extending/index.html) 部分。
22+
23+
3、告诉 pip 在安装你的软件包时要编译包里面的 C/C++ 代码为共享库,这个可以通过定制 setup 函数来完成。官方文档看这里 [setup](https://docs.python.org/3/distutils/setupscript.html)
24+
25+
26+
---
27+
28+
## 试用
29+
安装包已经上传到了 pypi ,你可以通过 pip3 install extend-cpython 完成安装
30+
``` bash
31+
pip3 install extend-cpython --upgrade
32+
33+
Installing collected packages: extend-cpython
34+
Running setup.py install for extend-cpython ... done
35+
Successfully installed extend-cpython-0.0.1
36+
37+
```
38+
试用 C/C++ 拓展中的功能。
39+
```python
40+
In [1]: from plugins import maths
41+
42+
In [2]: maths.plus_one(12305)
43+
Out[2]: 12306.0
44+
```
45+
46+
---
47+
48+
49+
## 1 实现业务逻辑
50+
因为这是一个模板项目,所以在这里只实现一个 + 1 的算法。
51+
```C++
52+
// 用 C++ 实现一个加一的函数
53+
double plus_one(double x)
54+
{
55+
return x + 1;
56+
}
57+
```
58+
59+
## 2 加上翻译代码
60+
61+
翻译代码负责把你的 C/C++ 代码包装成 *.py 一样的模块。
62+
```C++
63+
// 把 C/C++ 的一个函数包装成一个 Python 函数
64+
static PyObject *py_plus_one(PyObject *self,PyObject *args)
65+
{
66+
double x = 0,result = 0;
67+
PyArg_ParseTuple(args,"d",&x);
68+
result = plus_one(x);
69+
return Py_BuildValue("d",result);
70+
}
71+
72+
// 定义模块要包含的函数列表
73+
static PyMethodDef methods[] = {
74+
{"plus_one",py_plus_one,METH_VARARGS,"plus one"},
75+
{0,0,0,0}
76+
};
77+
78+
// 定义模块
79+
static struct PyModuleDef module = {
80+
PyModuleDef_HEAD_INIT,
81+
"plugins",
82+
"extend cpython",
83+
-1,
84+
methods
85+
};
86+
87+
// 定义模块的初始化方法
88+
PyMODINIT_FUNC PyInit_maths(void)
89+
{
90+
return PyModule_Create(&module);
91+
}
92+
93+
```
94+
95+
## 3 告诉 pip 安装时要怎么编译
96+
```python
97+
import os
98+
import re
99+
from setuptools import setup,Extension
100+
101+
setup(name='extend-cpython',
102+
#省略
103+
ext_modules = [Extension('plugins/maths',["src/maths.cpp"])],
104+
#省略
105+
)
106+
```
107+

0 commit comments

Comments
 (0)