Using a java socket from JNI / C++ code

后端 未结 5 1556
抹茶落季
抹茶落季 2021-01-02 05:02

I have a java app that creates a socket to talk to a server process, eg new java.net.Socket(String host, int port). This app includes a bunch of legacy c++ code that needs t

5条回答
  •  醉酒成梦
    2021-01-02 05:34

    Beware of solutions that poke around in JVM implementation specifics, they are liable to break in the future or with a different vendors VM. There is a way to do this portably using java.nio APIs. There are methods for communicating with channels from native code without copying buffers to/from the java heap.

    The basic idea will be to create a java.nio.SocketChannel in your java code to open the connection. Then in the C++ use NewDirectByteBuffer to create a java.nio.ByteBuffer instance that can be passed to the read/write methods of the channel instance.

    Look at JNI Enhancements Introduced in Version 1.4 of the Java 2 SDK and New I/O APIs for the details.

提交回复
热议问题