pip install cython pip install pyinstaller
编写文件compile.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize('AlgorithmIce/*.py'))
执行python compile.py build_ext(需要带参数)
使用cython编译pyx文件输出c和h文件(带cdef public等定义才会输出头文件),pyx添加
# distutils: language = c++输出cpp文件 或者cython --cplus输出
cython test.pyx //要导出的函数最好自己写,自动生成问题很多
生成c文件后,配置可以改成如下形式:
setup(ext_modules = Extension('name',source=['AlgorithmIce/*.py'],depends=[''])
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(Extension('AlgorithmIce',['AlgorithmIce/AlgorithmIce.py','AlgorithmIce/AMBase.py'])))
#方便调试用
chdir('build/lib.win-amd64-3.8')
system('copy /y tt.cp38-win_amd64.pyd ..\\..\\tt.pyd' )
chdir('../../')
system('del /q/s build')
执行python compile.py build_ext
下面是boost python的模块导出
using namespace boost::python;
BOOST_PYTHON_MODULE(Algorithm)
{
scope().attr("__doc__") = "boost.python Algorithm plugin";
class_<ClientApp, boost::noncopyable>("ClientApp", init<std::string,std::string,std::string>())
.def("run",&ClientApp::run)
.def("init",&ClientApp::init)
.def("start",&ClientApp::start)
.def("calc",&ClientApp::calc)
.def("stop",&ClientApp::stop)
.def("close",&ClientApp::close);
}
文件拷贝到python\lib\site-packages目录下,不用修改输出的文件名(或者修改名字本目录导入) 用depend打开pyd文件,查看导出函数
使用ctypes的方式加载函数(windll、oledll)
from ctypes import *
great_module = cdll.LoadLibrary('./great_module.dll')
print great_module.great_function(13)
或者vc++实现反射机制可以,通过python导入,可以查看zeroc-ice的IcePy模块(反射方式导入python,实现PyObject的对接)
参考:C++ REFLECTION FOR PYTHON BINDING python扩展的项目,使用swig把c++封装成python,https://github.com/rochacbruno/rust-python-example.git
swig地址:http://www.swig.org/
swig -python *.i 生成对应的类型调用文件和c代码(py文件中的模块带"_",swig模块也要带下划线)
或者使用ironpython(c#实现的python,支持反射)打包,rustpython打包
cpython区别于cython可以打包python解析器到模块中,效率比cython低
打包可执行文件比较简单,一个命令即可
pyinstall -F *.py (生成的文件已有一个exe,不加-F生成的文件较多)
使用python自带的工具打包
python setup.py bdist_wininst //set.py如上需要自己编辑 python setup.py bdist_wininst # 创建".exe"的文件 python setup.py bdist_msi # 创建".msi"的文件 python setup.py bdist --format=msi # 同样是创建"*.msi"的文件
链接失败:python扩展导入的库vs中是__thiscall,到extension中变成了__cdecl调用,所有找不到链接了,后面改用源码编译(不知道python内部参数怎么改的)
python中使用
print(os.getpid())打印出进程id,使用调试器附加调试 vc extension中extra_link_args添加
保证pdb和pyd的文件名相同就可以调试了
制作rpm包
python setup.py bdist_rpm # 创建"*.rpm"的文件,该命令需要在Linux操作系统上执行! python setup.py bdist --format=rpm # 同上
制作压缩包
python setup.py bdist --format=zip # 创建".zip"压缩文件 python setup.py bdist --format=gztar # 创建".tar.gz"文件