2.生成代码 thrift-0.9.2.exe --gen cpp a.thrift
3.开发
注意的是不要只看thrift的文件,要看生成的具体代码里面的接口函数是如何的(比如,该例子中,就用引用代替了返回值,需要额外注意)
server端
与python不同,c++会产出HelloWorld_server.skeleton.cpp的代码,直接在此基础上重写函数即可
g++ -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -Wall -I/usr/local/include/thrift HelloWorld_server.skeleton.cpp a_types.cpp a_constants.cpp HelloWorld.cpp -L/usr/local/lib -lthrift -o server
client端
g++ -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -Wall -I/usr/local/include/thrift c.cpp a_types.cpp a_constants.cpp HelloWorld.cpp -L/usr/local/lib -lthrift -o client
#include "HelloWorld.h"
#include "a_types.h"
#include <transport/TSocket.h>
#include <transport/TBufferTransports.h>
#include <protocol/TBinaryProtocol.h>
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using boost::shared_ptr;
using namespace std;
int main(int argc, char **argv)
{
boost::shared_ptr<TSocket> socket(new TSocket("localhost", 9090));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
transport->open();
HelloWorldClient c = HelloWorldClient(protocol);
employee e;
e.id = 1;
e.name = "1123";
string a = "123";
c.ping(a);
cout<<a<<endl;
string b;
c.sayHello(b,"1122",e);
transport->close();
return 0;
}
其他附录:
-DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H到底为什么要写上,我还真不知道为什么
不定义这两个宏目前没有发现什么不妥,并且按照其给出的编译连接分开的方法,也并没有用到这两个宏,很诡异
Compiling/Building the server
To quickly build a binary using a single command use:
g++ -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -Wall -I/usr/local/include/thrift *.cpp -L/usr/local/lib -lthrift -o something
Compiling
You need to point your compiler to the thrift include path (CXX flag: -I/usr/local/include/thrift
)
g++ -Wall -I/usr/local/include/thrift -c Something.cpp -o something.o g++ -Wall -I/usr/local/include/thrift -c Something_server.cpp -o server.o g++ -Wall -I/usr/local/include/thrift -c your_thrift_file_constants.cpp -o constants.o g++ -Wall -I/usr/local/include/thrift -c your_thrift_file_types.cpp -o types.o
Linking
You need to point your linker to the thrift library. (Linker flag: -lthrift
or -l/usr/local/lib/libthrift.so
)
g++ -L/usr/local/lib *.o -o Something_server -lthrift