Search code examples
c#java-native-interfacec++-cli

C# byte[] to jbytearray without Copying every Element


I am passing a byte array from C# to Java. Currently my C++ Code looks like this:

sendDocument(array<byte> ^arr) //Called by C# class
{ ...
    jbyteArray result = javaEnv->NewByteArray(arr->Length);
    jbyte *bytes = javaEnv->GetByteArrayElements(result, 0);
    for(int k = 0; k < arr->Length ; k++)
    {       
        bytes[k] = arr[k];
    }
    ... //Call Java method
}

Can i omit the Copying part somehow (or increase the performance differently)?

Edit: I managed to get it done wtih pointer work:

jbyteArray result = javaEnv->NewByteArray(arr->Length);
pin_ptr<unsigned char> pUnmanagedArr = &arr[0];
javaEnv->SetByteArrayRegion(result, 0, arr->Length, (jbyte*)pUnmanagedArr);

but how dirty is this approach?


Solution

  • I think that is a good approach for copying data. The only thing dirty about it is the type parameter you used with pin_ptr isn't textually the same as the type parameter used with arr—no real difference, though.

    You omitted the code sections that supply deal with javaEnv so be sure that the thread that calls sendDocument is initialized and uninitialized with the JVM (i.e. using AttachCurrentThread and DetachCurrentThread, or JNI_CreateJavaVM and DestroyJavaVM).