我尝试通过命名管道在两个进程之间发送一个对象,在C ++中使用ifstream和ofstream。我已经阅读并尝试了很多东西,但我的研究却没有任何结果。
我在对象的序列化过程中阻止了。 当我试图施放并发送到我的命名管道时,我无法将我的物体恢复到他的正常状态。
我尝试使用此代码,但在命名管道中传递后该对象未满:
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
class Obj {
public:
std::string text1;
std::string text2;
};
int main() {
mkfifo("fifo", 0666);
if (fork() == 0) //Receiving Side
{
std::ifstream fifo("fifo", std::ofstream::binary);
//Re-make the object
Obj *tmp = new Obj();
char *b = new char[sizeof(*tmp)];
//Receive from named pipe
fifo >> b;
//Recover the object
memcpy(&*tmp, b, sizeof(*tmp));
//Display object content
std::cout << tmp->text1 << std::endl << tmp->text2 << std::endl;
//!\ Output = "Some \n" /!\\
fifo.close();
delete tmp;
delete[] b;
}
else //Sending Side
{
std::ofstream fifo("fifo", std::ofstream::binary);
//Create the object
Obj *struct_data = new Obj();
struct_data->text1 = "Some text";
struct_data->text2 = "Some text";
char *b = new char[sizeof(*struct_data)];
//Serialize the object
memcpy((void *)b, &*struct_data, sizeof(*struct_data));
//Send to named pipe
fifo << b;
fifo.close();
wait(NULL);
delete[] b;
}
//delete struct_data;
return (0);
}
有人可以给我一个提示或示例吗?
谢谢! :)
答案 0 :(得分:2)
您需要正确序列化对象。像这样的东西(只做了一个成员,其余的将作为练习留给读者):
{{1}}
有关序列化的更多信息,请参阅https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html