简体   繁体   中英

Swig: passing unsigned char array from C++ to Java

I have a C++ function in a .cpp file; say unsigned char *myFunc() . How can I convert that array in a byte[] array in Java? I mean, in Java, I want to do something like:

byte[] b = myLib.myFunc();

I am using SWIG and appearently I need to define a kind of conversion from unsigned char to byte in the .i file, but I don't know exactly how.

Thank you in advance

Try returning a std::string instead of unsigned char* and %include <std_string.i> in your .i file. Thanks to std_string.i typemaps, you might end up with a byte[] on the receiving side. If you can change the return type of myFunc then create a wrapper via %inline , something like

%inline %{
    std::string myFuncStr() { return myFunc(); }
%}

If you want you can %rename myFuncStr to myFunc , thus hiding the fact that the myFunc exported to Java is actually a wrapper to the real myFunc .

If that doesn't work, Flexo's solution to Swig: convert return type std::string(binary) to java byte[] likely will.

I don't know about using swig but I do know that if you change your mind and want don't mind using JNI, then the following will work:

On the C++ side:

extern "C" jbyteArray JNIEXPORT Java_myPackageName_MyClassName_getByteArray(JNIEnv* env, jobject obj)
{
    jbyteArray byte_arr = env->NewByteArray(size);

    jbyte bytes[25];  //Some byte array you want to give to java. Could be an unsigned char[25].

    for (int i = 65; i < 90; ++i) //filling it with some A-Z ASCII characters.
    {
        bytes[i - 65] = i;
    }

    env->SetIntArrayRegion(byte_arr, 0, 25, &bytes[0]); //Fill our byte array

    return byte_arr; //return the byte array..
}

on the Java side:

package myPackageName;

class MyClassName
{
    static {
        System.loadLibrary("myByteArrayModule");
    }

    public static native byte[] getByteArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM