|
⇤ ← Revision 1 as of 2006-12-06 05:01:07
Size: 2131
Comment:
|
Size: 2146
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 3: | Line 3: |
| ''' | [:Pyrex:Pyrex] ''' |
[:Pyrex:Pyrex] 一个简单但完整的例子来测试pyrex调用已有lib库法。 ::-- ZoomQuiet [DateTime(2006-12-06T05:01:07Z)] TableOfContents
1. 坐以论道,起而行之
1.1. 准备
- 环境:ubuntu 6.06,python 2.4.3
1.2. 生成简单的lib
1,先生成简单的lib:
=>vi test.h
int tadd(int a, int b);
=>vi test.c
#include "test.h"
int tadd(int a, int b)
{
return a+b;
};
=>gcc -c test.c
生成test.o
=>ar -rsv libtest.a test.o
生成了 libtest.a 静态库
1.3. lib可用?
2,我们测试一下这个lib可以用吗?
=>vi ttest.c
#include <stdio.h>
#include "test.h"
void main(int argc, void * argv[])
{
int c=1;
c = tadd(1, 4);
printf("c = %d \r\n", c);
}
=>gcc ttest.c -ltest -L.
生成了a.out
./a.out 结果是:
c = 5证明我们的lib库是可以正常工作的
1.4. python的测试模块
3,写一个python的模块td,调用它libtest里的tadd()函数
写一个pyx,
=>vi td.pyx
cdef extern from "test.h":
int tadd(int i, int j)
def tdadd(int i, int j):
cdef int c
c=tadd(i, j)
return c就在这行调用的:c=tadd(i, j)了。
编译:
=>pyrexc td.pyx 生成 td.c =>gcc -c -fPIC -I/usr/include/python2.4/ td.c 生成td.c =>gcc -shared td.o -ltest -L. -o td.so 生成了td.so。这个就是python可以用的模块so了
1.5. 安装
=>vi setup.py
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name = "PyrexGuide",
ext_modules=[
Extension("td", ["td.pyx"], libraries = ["test"])
],
cmdclass = {'build_ext': build_ext}
)
=>python setup.py build_ext --inplace
1.6. 测试
>>> import td >>> dir(td) ['__builtins__', '__doc__', '__file__', '__name__', 'tdadd'] >>> td.tdadd(1,2) 3
呵呵,OK了。
等会再试一试ctypes
