Search code examples
java-native-interfacegrpcgrpc-java

Convert gRPC channel from C++ to Java


I have a library, that already uses a C++ version of gRPC, and I need to implement a Java wrapper. Thus, I need to use Java Native Interface (JNI) to convert std::shared_ptr<grpc::Channel> to gRPC-Java Channel.

More specifically, I need to implement the following Java function:

public native ManagedChannel CreateChannel(String address);

that references this existing C++ function:

std::shared_ptr<grpc::Channel> CreateChannel(std::string address);

Is it possible to do this?


Solution

  • Possible? Yes. Easy? No.

    The Channel/ManagedChannel API mainly has the newCall() method. Implementing that method would be annoying as you'd need to map MethodDescriptor and CallOptions to the C++ equivalents. But the bigger problem is it returns a ClientCall which would take more work to implement.

    C++ uses a different API for flow control than Java, so you'd have to map those. The C++ callback API would be ideal in this situation, but it not currently available (time of writing: 2019 Q4). So that would mean creating threads and using the async API.