我正在尝试通过 Erlang 端口将 Erlang 程序与简单的 Qt 窗口应用程序进行通信。
问题是 Qt 窗口事件 (on_pushButton_clicked()
) 的结果仅在窗口关闭后显示在 Erlang 端口中,而不是在按下按钮时:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "stdio.h"
#include "choosefileform.h"
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
fprintf(stdout, "window_input:");
printf(ui->lineEdit->text().toAscii());
printf("~n");
ChooseFileForm* fn = new ChooseFileForm();
this->close();
fn->show();
}
Erlang(发送消息在这里什么都不做,我们有兴趣从 Qt 获取数据):
connect(Message) ->
Cmd = "./myqtwindowapp \n",
Port = open_port({spawn,Cmd}, [stream,use_stdio,exit_status]),
Payload = string:concat(Message, "\n"),
erlang:port_command(Port, Payload),
receive
{Port, {data, Data}} ->
?DBG("Received data: ~p~n", [Data]),
Other ->
io:format("Unexpected data: ~p~n", [Other])
after 15000 ->
?DBG("Received nothing~n", [])
end.
运行它并在窗口中填充文本字段的结果是什么(Erlang 什么也得不到,只是在 receive
子句中等待):
只有当我手动关闭窗口时 Erlang 说:
Received data: "window_input:hello"
那么,为什么我不立即从 Qt 获取数据到 Erlang 端口?
更新。解决方案:
解决方案是 flush() Qt 的缓冲区:
代替 fprintf(stdout, "window_input:");
我用了
cin >> c;
cout << c;
cout.flush();
它奏效了。
附言但是,我不明白为什么在控制台中测试相同的 Qt 应用程序时没有发生此问题 - 它会立即返回数据,我在窗口中填写了文本字段(即在事件发生时)。
最佳答案
我对 C++ 的经验不多,但您似乎没有从您的端口刷新数据。 (而且 "~n"
不是 C++ 中的新行,这不是大小写,因为您使用 stream
模式而不是 line
。)
关于c++ - Erlang 端口无法正确处理 C++/Qt 回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8497051/