【问题标题】:Call function from python in C++在 C++ 中从 python 调用函数
【发布时间】:2021-02-07 13:53:03
【问题描述】:

我目前正在开发一个带有单独 cli 和 gui 的项目。 gui 部分是用 C++ 编写的,以保持可执行文件很小。我用pyinstaller编译了我的python程序,需要从C++程序中调用一些函数。

Python部分:

import configparser
def getconfig() -> list:
    config = configparser.ConfigParser()
    config.read("config.ini")
    section1 = config["general"]
    section2 = section["section2"]
    return [section1, section2] #should be a list of dict?

通过 pyinstaller --onefile --clean myprogram.py 编译

我想用 C++ 做的是:

//please correct me if this is the wrong type, 
//i know i probably need to do a bit of parsing between python and C++ types

std::vector<std::unordered_map<std::string, std::string>> > = myprogram.getconfig()

我只是不想再次在 C++ 中进行配置解析,或者你会推荐这个,因为它可能更容易调用已编译的 python 二进制文件?

这个程序只需要在linux上运行,windows不是必须的。

【问题讨论】:

  • 这个问题你解决了吗?如果是这样,请将其标记为已关闭,或者如果我的回答对您有任何帮助,请发表评论。

标签: python c++ pyinstaller static-linking


【解决方案1】:

如果您只打算在兼容 POSIX 的系统(即 GNU/Linux)上运行,您可以生成一个新进程来运行 Python 脚本,例如使用 C 函数exec。示例:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
{
        char* args[] = { "pythonscript.py", NULL };
        int t = execv("pythonscript.py", args);
        if(t < 0) printf("%s\n", strerror(errno));
        return 0;
}

然后在pythonscript.py中:

#!/usr/bin/python3
print("hello, world!")

这个技巧也适用于 bash 脚本。 脚本必须是可执行的,所以记得运行chmod +x pythonscript.py

编辑: 您可能需要使用管道或其他机制进行进程间通信。 (这不是我的专长!)

【讨论】:

猜你喜欢
  • 2013-08-30
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2016-03-25
  • 2016-05-29
  • 1970-01-01
相关资源
最近更新 更多