|
2 | 2 | 第十五章:C语言扩展
|
3 | 3 | =============================
|
4 | 4 |
|
5 |
| -本章着眼于从Python访问C代码的问题。许多Python内置库是用C写的,访问C是让Python的对现有库进行交互一个重要的组成部分。这也是一个当你面临从Python 2 到 Python 3扩展代码的问题。虽然Python提供了一个广泛的编程API,实际上有很多方法来处理C的代码。相比试图给出对于每一个可能的工具或技术的详细参考,我么采用的是是集中在一个小片段的C++代码,以及一些有代表性的例子来展示如何与代码交互。这个目标是提供一系列的编程模板,有经验的程序员可以扩展自己的使用。 |
| 5 | +本章着眼于从Python访问C代码的问题。许多Python内置库是用C写的, |
| 6 | +访问C是让Python的对现有库进行交互一个重要的组成部分。 |
| 7 | +这也是一个当你面临从Python 2 到 Python 3扩展代码的问题。 |
| 8 | +虽然Python提供了一个广泛的编程API,实际上有很多方法来处理C的代码。 |
| 9 | +相比试图给出对于每一个可能的工具或技术的详细参考, |
| 10 | +我么采用的是是集中在一个小片段的C++代码,以及一些有代表性的例子来展示如何与代码交互。 |
| 11 | +这个目标是提供一系列的编程模板,有经验的程序员可以扩展自己的使用。 |
6 | 12 |
|
7 | 13 | 这里是我们将在大部分秘籍中工作的代码:
|
8 | 14 |
|
9 |
| -.. code-block:: c |
| 15 | +:: |
10 | 16 |
|
11 | 17 | /* sample.c */_method
|
12 | 18 | #include <math.h>
|
|
62 | 68 | return hypot(p1->x - p2->x, p1->y - p2->y);
|
63 | 69 | }
|
64 | 70 |
|
65 |
| -This code contains a number of different C programming features. First, there are a few |
66 |
| -simple functions such as gcd() and is_mandel(). The divide() function is an example |
67 |
| -of a C function returning multiple values, one through a pointer argument. The avg() |
68 |
| -function performs a data reduction across a C array. The Point and distance() function |
69 |
| -involve C structures. |
70 |
| - |
71 |
| - |
72 |
| -For all of the recipes that follow, assume that the preceding code is found in a file named |
73 |
| -sample.c, that definitions are found in a file named sample.h and that it has been compiled |
74 |
| -into a library libsample that can be linked to other C code. The exact details of |
75 |
| -compilation and linking vary from system to system, but that is not the primary focus. |
76 |
| -It is assumed that if you’re working with C code, you’ve already figured that out. |
| 71 | +这段代码包含了多种不同的C语言编程特性。 |
| 72 | +首先,这里有很多函数比如 ``gcd()`` 和 ``is_mandel()`` 。 |
| 73 | +``divide()`` 函数是一个返回多个值的C函数例子,其中有一个是通过指针参数的方式。 |
| 74 | +``avg()`` 函数通过一个C数组执行数据聚集操作。``Point`` 和 ``distance()`` 函数涉及到了C结构体。 |
77 | 75 |
|
| 76 | +对于接下来的所有小节,先假定上面的代码已经被写入了一个名叫“sample.c”的文件中, |
| 77 | +然后它们的定义被写入一个名叫“sample.h”的头文件中, |
| 78 | +并且被编译为一个库叫“libsample”,能被链接到其他C语言代码中。 |
| 79 | +编译和链接的细节依据系统的不同而不同,但是这个不是我们关注的。 |
| 80 | +如果你要处理C代码,我们假定这些基础的东西你都掌握了。 |
78 | 81 |
|
79 | 82 | Contents:
|
80 | 83 |
|
|
0 commit comments