Efficient data transfer from Java to C++ on windows

后端 未结 11 1250
我在风中等你
我在风中等你 2021-01-18 03:39

I\'m looking to stream lots of data (up to ~1 Gbit) from Java to a C++ application (both on the same machine). I\'m currently using a FIFO on Linux but need a Windows soluti

11条回答
  •  心在旅途
    2021-01-18 04:11

    If it's a big chunk of data in "one" function call I would recommend JNI.

    Take a look at this:Sharing output streams through a jni interface

    Snippet from the article, it transfert data from c++ to java, the opposite would be also easy to do:

    In all, the general strategy for sharing binary data (A/V files, images, etc.) from C with Java requires byte arrays. You create a Java byte array in C like this:

    const char[] rawData = {0,1,2,3,4,5,6,7,8,9}; //Or get some raw data from somewhere
    int dataSize = sizeof(rawData);
    printf("Building raw data array copy\n");
    jbyteArray rawDataCopy = env->NewByteArray(dataSize);
    env->SetByteArrayRegion(rawDataCopy, 0, dataSize, rawData);
    

    And pass it to Java like this:

    printf("Finding callback method\n");
    //Assumes obj is the Java instance that will receive the raw data via callback
    jmethodID aMethodId = env->GetMethodID(env->GetObjectClass(obj),"handleData","([B)V");
    if(0==aMethodId) throw MyRuntimeException("Method not found error");
    printf("Invoking the callback\n");
    env->CallVoidMethod(obj,aMethodId, &rawDataCopy);
    

    you would have a Java object that looked something like this:

    public class MyDataHandler {
      OutputStream dataStream;
      public MyDataHandler(OutputStream writeTo) { dataStream = writeTo;}
      public void handleData(byte[] incomingData) { dataStream.write(incomingData); }
    }
    

    That handler would be passed to C via native method like so:

    public class NativeIntegration {
      public native void generateBinaryWithHandler(MyDataHandler handler);
    
      //Here we assume response is something like a network stream
      public void doCallNativeFunction(ResponseStream response) {
        MyDataHandler handler = new MyDataHandler(response);
        generateBinaryWithHandler(handler);
      }
    }
    

    Also, you can use other technologies: CORBA, ASN.1 (ASN.1 tool), UDP or TCP

提交回复
热议问题