开发者

How to pass java.net.Socket to a C++ DLL function waiting for `BoostSocket.assign(tcp::v4(), nativeSocketFromJava);`

开发者 https://www.devze.com 2023-03-25 14:54 出处:网络
So I wonder is it possible and how to pass socket from ja开发者_C百科va to some DLL library waiting for native for this OS socket? Could any one provide an example? Is it anyhow possible to use org.ap

So I wonder is it possible and how to pass socket from ja开发者_C百科va to some DLL library waiting for native for this OS socket? Could any one provide an example? Is it anyhow possible to use org.apache.tomcat.jni.Socket for it?


First thing first - we need to get a file descriptor of java.net.Socket. That is possible to do using reflection mechanism. The idea is to get access to java.io.FileDescriptor on the java.net.SocketImpl and then get a native socket descriptor. See DualStackPlainSocketImpl.java for code snippets (this method is also pointed out by Zoran Regvart here).

Another method is to use JNI, as discussed here, here is an example:

static int getFd(JNIEnv *env, jobject sock)
{
    JNIEnv e = *env;
    jclass clazz;
    jfieldID fid;
    jobject impl;
    jobject fdesc;

    /* get the SocketImpl from the Socket */
    if (!(clazz = e->GetObjectClass(env,sock)) ||
        !(fid = e->GetFieldID(env,clazz,"impl","Ljava/net/SocketImpl;")) ||
        !(impl = e->GetObjectField(env,sock,fid))) return -1;

    /* get the FileDescriptor from the SocketImpl */
    if (!(clazz = e->GetObjectClass(env,impl)) ||
        !(fid = e->GetFieldID(env,clazz,"fd","Ljava/io/FileDescriptor;")) ||
        !(fdesc = e->GetObjectField(env,impl,fid))) return -1;

    /* get the fd from the FileDescriptor */
    if (!(clazz = e->GetObjectClass(env,fdesc)) ||
        !(fid = e->GetFieldID(env,clazz,"fd","I"))) return -1;

    /* return the descriptor */
    return e->GetIntField(env,fdesc,fid);
}

I also suppose you are talking about Boost.Asio's TCP socket. If so, then you have to associate a native socket with Asio's socket object using assign method.

Be aware that this solution may not work for certain Java implementations as it is using internal details of the implementation that is not guaranteed to stay the same. Plus, make sure the is no concurrency (i.e. Java is not trying to read from the same socket descriptor in parallel) etc. In other words - use at your own risk.

Hope it helps. Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消