[英]Call function from python in C++
我目前正在开发一个具有单独 cli 和 gui 的项目。 gui 部分是用 C++ 编写的,以保持可执行文件很小。 我用pyinstaller编译了我的python程序,需要从C++程序中调用一些函数。
蟒蛇部分:
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就不需要了。
如果您只打算在 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
。
编辑:您可能需要使用管道或其他机制进行进程间通信。 (这不是我的专长!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.