V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
YUCOAT
V2EX  ›  程序员

cpp 如何嵌入 Python 解释器

  •  
  •   YUCOAT · 2015-04-16 22:05:07 +08:00 · 4175 次点击
    这是一个创建于 3296 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我想在我的cpp程序里调用Python脚本函数,然后照着网上的资料,写了一个demo,运行成功了。然后我把我的demo、py的dll、py脚本,MSVCxxx之类的文件挪到另外一台没有安装Python解释器的电脑上,我的demo跑不起来了。

    很显然,我的demo是通过python的dll调用了我本机的Python解释器来运行Python脚本的。现在我需要让我的cpp程序在客户的电脑上也运行Python脚本,而客户的电脑是没有安装Python解释器的,那我应该怎么做呢?

    我没有找到类似的文档,谢谢大家的回答。
    8 条回复    2015-04-17 21:59:17 +08:00
    timonwong
        1
    timonwong  
       2015-04-16 22:13:43 +08:00
    先看官方文档:
    https://docs.python.org/2/extending/embedding.html

    一些库:
    超级重量级的 boost::python

    如果你已经在本机能运行了,你需要打包:
    1. Python??.dll 以及依赖 (比如 msvc 运行库)
    2. python stdlib, (可以打包为 zip, 比如 python27.zip, 然后加入 PYTHONPATH 环境变量)
    YUCOAT
        2
    YUCOAT  
    OP
       2015-04-16 22:51:19 +08:00
    @timonwong

    我已经尝试过了,把我机器上的Python34文件复制到没有安装的电脑上,然后把我的exe和py都放到对面机器上的Python34里,把msvc之类的必要dll页复制过去就能直接运行我的程序。可以不用设置环境变量。
    timonwong
        3
    timonwong  
       2015-04-16 23:03:07 +08:00   ❤️ 2
    @YUCOAT
    我的意思是这样的

    - 你的程序.exe
    - python34.dll
    - python34.zip
    - msvcrt 相关 dll

    python34.zip 是 Python34\Lib 打包
    Py_SetPath(L"xxx\\python34.zip");
    YUCOAT
        4
    YUCOAT  
    OP
       2015-04-17 00:11:20 +08:00
    @timonwong 了解啦~
    Septembers
        5
    Septembers  
       2015-04-17 19:44:25 +08:00
    @timonwong
    /t/180051#r_1933214
    在Python-2.7.3/Modules/python.c的main函数的首行加入
    Py_SetPath(L"./python-stdlib.zip");
    会编译失败 请问需要改写才能编译通过并运行 谢谢
    timonwong
        6
    timonwong  
       2015-04-17 20:30:22 +08:00
    Septembers
        7
    Septembers  
       2015-04-17 21:36:44 +08:00
    @timonwong
    ➜ Python-2.7.3 ./python
    [1] 19515 segmentation fault (core dumped) ./python
    timonwong
        8
    timonwong  
       2015-04-17 21:59:17 +08:00
    @Septembers
    1. 为什么运行 python,这里的上下文是 embedding 不是 extending...
    2. PySys_SetPath 接收的是 char * 不是 wchart_t *
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5151 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:32 · PVG 17:32 · LAX 02:32 · JFK 05:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.