将c ++与python链接起来

时间:2018-03-10 13:10:15

标签: python c++

我使用gcc编译器在c ++中创建了一个聊天机器人,它使用基本文件处理操作来处理用户查询,但现在我想升级它。为此我想到将我的代码链接到互联网,打开Windows程序并提供它GUI interphase.As我最近学过python,我知道开发一个GUI并将代码连接到互联网比在c ++中容易得多。所以我想把我的c ++代码与python联系起来。我怎么能这样做以便基本代码保持不变,但我使用python将其链接到互联网。我搜索并发现了cpython,py ++和swig但是因为我是新手我不太了解。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:0)

您可能需要为c ++代码编写python包装器。您可以将boost::python用于此

答案 1 :(得分:0)

在聊天机器人对stdin / stdout进行读/写操作时,最简单的解决方案是使用subprocess模块,因为它需要的量最少。在这里,您将在一个单独的过程中启动您的聊天机器人,然后就像从终端一样使用它。

下面是一些可以与您的C ++聊天机器人交谈的基本实现(它只是使用cat来回显输入作为示例)。它的say方法是阻塞的,并且假定每行输入只有一行输出。如果您的聊天框有多行响应,它将会遇到麻烦。

from subprocess import Popen, PIPE
import io

CMD = 'cat'

class Chatbot:
    def __init__(self):
        self._chatbot_proc = Popen(CMD, stdin=PIPE, stdout=PIPE)
        # You may wish to add encoding='ascii' to the TextIOWrapper constructor
        # if your chatbot is not UTF-aware.
        self._input = io.TextIOWrapper(self._chatbot_proc.stdin, line_buffering=True)
        self._output = io.TextIOWrapper(self._chatbot_proc.stdout)

    def close(self):
        self._input.close()
        self._output.close()
        self._chatbot_proc.close()

    def say(self, request):
        assert '\n' not in request
        self._input.write(request)
        self._input.write('\n')
        return self._output.readline().rstrip()

def main():
    chatbot = Chatbot()
    try:
        while True:
            user_input = input()
            print('sending:', repr(user_input))
            chatbot_response = chatbot.say(user_input)
            print('chatbot said:', repr(chatbot_response))
    except Exception:
        chatbot.close()
        raise

if __name__ == "__main__":
    main()