求C++调用gRPC客户端生成的共享库的实现示例
调用gRPC客户端共享库的C++示例
下面是完整的实现流程,包含共享库接口定义、gRPC客户端逻辑封装、外部调用示例及编译步骤:
1. 定义共享库公共头文件(grpc_client_wrapper.h)
这个头文件对外暴露调用gRPC服务的接口,用extern "C"避免C++名字修饰问题,保证跨语言/编译单元的兼容性:
#ifndef GRPC_CLIENT_WRAPPER_H #define GRPC_CLIENT_WRAPPER_H #ifdef _WIN32 #define GRPC_WRAPPER_API __declspec(dllexport) #else #define GRPC_WRAPPER_API __attribute__((visibility("default"))) #endif #ifdef __cplusplus extern "C" { #endif // 调用gRPC服务的核心接口 // input: 请求字符串 // output: 用于存储响应结果的缓冲区 // output_max_len: 缓冲区最大长度(需留足字符串结束符空间) // 返回值: 0=调用成功,-1=参数错误,-2=gRPC服务调用失败 GRPC_WRAPPER_API int CallGrpcService(const char* input, char* output, int output_max_len); #ifdef __cplusplus } #endif #endif // GRPC_CLIENT_WRAPPER_H
2. 共享库实现(grpc_client_wrapper.cpp)
内部封装gRPC客户端逻辑,这里假设你已经通过proto文件生成了echo.grpc.pb.h、echo.pb.h等头文件(proto定义一个简单的Echo服务,接收字符串并返回):
#include "grpc_client_wrapper.h" #include "echo.grpc.pb.h" #include <grpcpp/grpcpp.h> #include <string> #include <cstring> using grpc::Channel; using grpc::ClientContext; using grpc::Status; using echo::EchoRequest; using echo::EchoResponse; using echo::EchoService; // gRPC客户端类封装 class EchoClient { public: EchoClient(std::shared_ptr<Channel> channel) : stub_(EchoService::NewStub(channel)) {} std::string SendEchoRequest(const std::string& msg) { EchoRequest req; req.set_message(msg); EchoResponse resp; ClientContext ctx; Status status = stub_->Echo(&ctx, req, &resp); if (status.ok()) { return resp.message(); } else { return "[Error] " + status.error_message(); } } private: std::unique_ptr<EchoService::Stub> stub_; }; // 实现对外暴露的接口 int CallGrpcService(const char* input, char* output, int output_max_len) { // 参数合法性校验 if (!input || !output || output_max_len <= 0) { return -1; } // 初始化gRPC客户端,连接到服务端 EchoClient client(grpc::CreateChannel( "localhost:50051", grpc::InsecureChannelCredentials() )); // 发起请求并获取结果 std::string result = client.SendEchoRequest(input); // 将结果写入输出缓冲区(避免越界) size_t copy_len = std::min(result.size(), static_cast<size_t>(output_max_len - 1)); strncpy(output, result.c_str(), copy_len); output[copy_len] = '\0'; // 根据结果返回状态码 return result.find("[Error]") == 0 ? -2 : 0; }
3. 调用共享库的C++程序(main.cpp)
外部程序通过头文件调用共享库接口:
#include "grpc_client_wrapper.h" #include <iostream> #include <cstring> int main() { const char* request_msg = "Hello gRPC from shared library!"; char response_buf[256]; memset(response_buf, 0, sizeof(response_buf)); int ret = CallGrpcService(request_msg, response_buf, sizeof(response_buf)); if (ret == 0) { std::cout << "服务响应: " << response_buf << std::endl; } else { std::cerr << "调用失败,错误码: " << ret << ", 详情: " << response_buf << std::endl; } return 0; }
4. 编译步骤
Linux环境
# 编译共享库(链接gRPC和Protobuf依赖) g++ -fPIC -shared grpc_client_wrapper.cpp echo.pb.cc echo.grpc.pb.cc -o libgrpc_client_wrapper.so `pkg-config --cflags --libs grpc++ protobuf` # 编译主程序并运行 g++ main.cpp -o grpc_client_app -L. -lgrpc_client_wrapper export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH ./grpc_client_app
Windows环境(MSVC编译器)
# 编译共享库 cl /LD grpc_client_wrapper.cpp echo.pb.cc echo.grpc.pb.cc ^ /I"D:\grpc\include" /I"D:\protobuf\include" ^ /link "D:\grpc\lib\grpc++.lib" "D:\protobuf\lib\libprotobuf.lib" # 编译主程序 cl main.cpp ^ /I"D:\grpc\include" ^ /link grpc_client_wrapper.lib grpc++.lib libprotobuf.lib
内容的提问来源于stack exchange,提问作者sama
相关产品推荐
相关产品推荐

