2

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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Schollii, I'd like to test your solution. But at the moment I'm having some errors, that I THINK might depend on the fact that my unsigned char* contains any ASCII character also greater than 128
0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.