我找不到关于如何使用 apache thrift 通过共享内存进行 ipc 通信的足够示例。我的目标是在 thrift 的帮助下序列化现有的类,然后通过共享内存发送到另一个进程,在该进程中我在 thrift 的帮助下再次反序列化它。现在我正在使用 TMemoryBuffer 和 TBinaryProtocol 来序列化数据。虽然这有效,但我不知道如何将其写入共享内存。
到目前为止,这是我的代码:
#include "test_types.h"
#include "test_constants.h"
#include "thrift/protocol/TBinaryProtocol.h"
#include "thrift/transport/TBufferTransports.h"
int main(int argc, char** argv)
{
int shID;
char* myPtr;
Person* dieter = new Person("Dieter", "Neuer");
//Person* johann = new Person("Johann", "Liebert");
//Car* ford = new Car("KLENW", 4, 4);
PersonThrift dieterThrift;
dieterThrift.nachName = dieter->getNachname();
dieterThrift.vorName = dieter->getVorname();
boost::shared_ptr<apache::thrift::transport::TMemoryBuffer> transport(new apache::thrift::transport::TMemoryBuffer);
boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> protocol(new apache::thrift::protocol::TBinaryProtocol(transport));
test thriftTest;
thriftTest.personSet.insert(dieterThrift);
u_int32_t size = thriftTest.write(protocol.get());
std::cout << transport.get()->getBufferAsString();
shID = shmget(1000, 100, IPC_CREAT | 0666);
if (shID >= 0)
{
myPtr = (char*)shmat(shID, 0, 0);
if (myPtr==(char *)-1)
{
perror("shmat");
}
else
{
//myPtr = protocol.get();
}
}
getchar();
shmdt(myPtr);
}
主要问题是零件
//myPtr = protocol.get();
如何使用 thrift 以便将反序列化数据写入 myPtr(从而写入共享内存)。我想 TMemoryBuffer 可能已经是一个坏主意了。正如你所看到的,我对此并没有真正的经验。
提前致以亲切的问候和感谢
Michael
再次阅读问题并仔细查看代码后……您就快到了。你犯的错误是查看协议,它没有给你任何数据。相反,你必须询问交通工具,就像你已经做的那样
std::cout << transport.get()->getBufferAsString();
获取原始数据的方式非常相似,只需使用getBuffer(&pbuf, &sz);
反而。使用这个,我们得到这样的东西:
// query buffer pointer and data size
uint8_t* pbuf;
uint32_t sz;
transport.get()->getBuffer(&pbuf, &sz);
// alloc shmem blöock of adequate size
shID = shmget(1000, sz, IPC_CREAT | 0666);
if (shID >= 0)
{
myPtr = (char*)shmat(shID, 0, 0);
if (myPtr==(char *)-1)
{
perror("shmat");
}
else
{
// copy serialized data into shared memory
memcpy( myPtr, pbuf, sz);
}
}
由于 shmget() 可能会为您提供比请求的更大的块,因此额外使用框架运输,它自动携带序列化数据中的真实数据大小。后者的一些示例代码可以在测试客户端或服务器代码 https://github.com/apache/thrift/blob/master/test/cpp/src/TestClient.cpp.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)