不使用子过程直接将Python对象传递给C++程序

2024-04-20 04:42:46 发布

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

我有一个C++程序,通过终端,把文本文件作为输入并生成另一个文本文件。我从Python脚本执行这个程序,它首先产生所说的文本字符串,将它存储到文件中,运行C++程序作为子进程,并将创建的文件作为输入,并将输出文本文件解析为Python对象。你知道吗

是否可以不使用子进程调用来执行此操作?换句话说,是否可以避免读写,只需在Python环境中运行以文本字符串作为输入的C++程序,然后在Python环境中再次捕获输出?你知道吗

对于代码,我引用了this IPython notebook中的函数community_detection_multiplex。你知道吗


Tags: 文件对象函数字符串代码文本程序脚本
1条回答
网友
1楼 · 发布于 2024-04-20 04:42:46

您可以使用ctypes
它要求C++函数用^ {CD1}}包起来,并编译成C代码。你知道吗

< >你的C++函数看起来像:

char* changeString(char* someString)
{
    // do something with your string
    return someString;
}

您可以从python中这样调用它:

import ctypes as ct

yourString = "somestring"
yourDLL = ct.CDLL("path/to/dll") # assign the dll to a variable
cppFunc = yourDLL.changeString # assign the cpp func to a variable
cppFunc.restype = ct.c_char_p # set the return type to a string
returnedString = cppfunc(yourString.encode('ascii')).decode()

现在returnedString将拥有已处理的字符串。你知道吗

相关问题 更多 >