Poperton
Poperton

Reputation: 2206

Conversion between jboolean* and uint64_t*

I'm trying to convert a jbooleanArray with 128 elements (always) to a C++ array of bools with 128 elements also.

extern "C" {
JNIEXPORT jboolean  Java_com_app_flutter_1app_JNI_loadBufferNative(
        JNIEnv *env, jbooleanArray jMidiNotes) {
    bool midiNotes[128] = {false};
    *reinterpret_cast<uint64_t*>(midiNotes) = *env->GetBooleanArrayElements(jMidiNotes, nullptr);
    *reinterpret_cast<uint64_t*>(midiNotes + 64) = *env->GetBooleanArrayElements(jMidiNotes + 64, nullptr);

I believe GetBooleanArrayElements returns jboolean*, and it looks like a jboolean is uint8_t in C++ (strange).

What am I doing wrong here? I get a crash JNI DETECTED ERROR IN APPLICATION: use of invalid jobject 0x7ff426b390.

Since jboolean = uint8_t I also tried

    *reinterpret_cast<uint64_t*>(midiNotes + 64) = *env->GetBooleanArrayElements(jMidiNotes + 8, nullptr);

but I get the same crash

Upvotes: 0

Views: 116

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33875

You can't do pointer arithmetic on object handles like that:

*reinterpret_cast<uint64_t*>(midiNotes + 64) = *env->GetBooleanArrayElements(jMidiNotes + 64, nullptr);

You should first get a pointer to the array elements using GetBooleanArrayElements and then do pointer arithmetic on that pointer. For instance, do like this:

extern "C" {
JNIEXPORT jboolean  Java_com_app_flutter_1app_JNI_loadBufferNative(
    JNIEnv *env, jbooleanArray jMidiNotes) {
    bool midiNotes[128] = {false};
    jboolean* values = env->GetBooleanArrayElements(jMidiNotes, nullptr);
    std::copy(values, values + 128, midiNotes);

Upvotes: 2

Related Questions