新建立一个 ext_build.py 用于生成扩展
# ext_build.py
import numpy as np
import cffi
ffi = cffi.FFI()
ffi.cdef("""int add(int a, int b);""")
ffi.cdef("""int sub(int a, int b);""")
ffi.set_source('_ext', """
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
""")
if __name__ == '__main__':
ffi.compile(verbose=True)
ffi.cdef 表示声明一个函数,ffi.set_source 第一个参数为扩展模块的名字,第二个参数为函数的定义。
然后执行 python ext_build.py
在 Windows 系统下大概会有如下显示
generating .\_ext.c
(already up-to-date)
the current directory is '**省略**'
running build_ext
building '_ext' extension
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\ProgramData\Anaconda3\include -IC:\ProgramData\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" "-ID:\Microsoft Visual Studio\VC98\atl\include" "-ID:\Microsoft Visual Studio\VC98\mfc\include" "-ID:\Microsoft Visual Studio\VC98\include" /Tc_ext.c /Fo.\Release\_ext.obj
_ext.c
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\ProgramData\Anaconda3\libs /LIBPATH:C:\ProgramData\Anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10240.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x64" "/LIBPATH:D:\Microsoft Visual Studio\VC98\mfc\lib" "/LIBPATH:D:\Microsoft Visual Studio\VC98\lib" /EXPORT:PyInit__ext .\Release\_ext.obj /OUT:.\_ext.cp36-win_amd64.pyd /IMPLIB:.\Release\_ext.cp36-win_amd64.lib
_ext.obj : warning LNK4197: 多次指定导出“PyInit__ext”;使用第一个规范
正在创建库 .\Release\_ext.cp36-win_amd64.lib 和对象 .\Release\_ext.cp36-win_amd64.exp
正在生成代码
已完成代码的生成
然后目录下生成了 _ext.cp36-win_amd64.pyd 这一个包。
新建一个 demo 测试一下
# demo.py
from _ext import ffi, lib
print(lib.add(2, 3))
print(lib.sub(2, 3))
输出
5
-1
通过。