C++中的Python调用函数

2024-09-23 22:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在处理一个使用单独cli和gui的项目。GUI部分用C++编写,以保持可执行的小。我用pythSudio编译了python程序,需要从C++程序调用一些函数。p>

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二进制可能比较容易?p>

这个程序只需要在linux上运行,不需要windows


Tags: of项目程序configstringcliguiconfigparser
1条回答
网友
1楼 · 发布于 2024-09-23 22:30:27

如果您仅计划在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

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

相关问题 更多 >