手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

使用C/C++写Python模块

[日期:2016-07-13] 来源:Linux社区  作者:zhaoweiwei [字体:大 中 小]

3 其他编译方式

下面介绍另一种用Python Script来生成.pyd文件的方法,新建一个Python脚本——CreatePyd.py,其内容如下:

 
from distutils.core import setup, Extension
ModuleInfo = Extension("testClass", sources = [r"main.cpp"])
setup(name             = "testClass",
      version          = "1.0",
      description      = "This module created by C++ weiwei.Zhao",
      author           = 'weiwei.zhao',
      author_email     = 'weiwei22844@hotmail.com',
      license          = "You can copy this program to anywhere.",
      url              = "http://zhaoweiwei.top",
      long_description = '''This is really just a demo!''',
      platforms        = "Windows",
      ext_modules      = [ModuleInfo]
     )

内容解释:先导入所需的Python模块,然后用Extension函数关联一个Cpp源文件一个要生成的模块名——注意:没有.pyd后缀。然后调用setup函数生成一个名字name为testClass的模块,版本version为1.0,描述description,作者信息author,作者邮箱author_email,还其平台platforms等等有用的信息!

最后调用:python CreateDLL.py build

经过编译后,就会新生成一个build目录,在build/lib.win32-2.7下你可以找到testClass.pyd文件。

需要注意的是编译脚本默认使用VS编译器,所以电脑上要安装VS,如果电脑上没有安装VS而是有MingW环境,则类似的可以使用MingW环境中gcc进行编译:

注意:为了使相关程序都能顺利找见,上图是在MingW的Shell命令行,而不是普通的windows Command命令行。

4 模块部署安装

一般来说,setup.py参数说明

#python setup.py build     # 编译

#python setup.py install    # 安装

#python setup.py sdist      # 生成压缩包(zip/tar.gz)

#python setup.py bdist_wininst  #生成NT平台安装包(.exe)

#python setup.py bdist_rpm  #生成rpm包

或者直接"bdist 包格式",格式如下:

#python setup.py bdist --help-formats

  --formats=rpm      RPM distribution

  --formats=gztar    gzip'ed tar file

  --formats=bztar    bzip2'ed tar file

  --formats=ztar    compressed tar file

  --formats=tar      tar file

  --formats=wininst  Windows executable installer

  --formats=zip      ZIP file

下图说明了windows安装程序生成过程,在dist目录下有windows的安装程序testClass-1.0.win32-py2.7.exe

需要说明的是如果生成的testClass.pyd依赖于其他库文件,如在我的环境下用MingW生成的testClass.pyd要依赖libgcc_s_dw2-1.dll和libstdc++-6.dll两个文件,生成安装包时需把这两个文件和testClass.pyd放到一起,如放到build/lib.win32-2.7目录下,之后生成的安装文件testClass-1.0.win32-py2.7.exe会包含着两个文件,如果不这样做在导入testClass时会导致导入失败,提示类似:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed: 找不到指定的程序。

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133126.htm

linux
相关资讯       Python模块