0

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

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • The jvm might do optimizations with booleans in arrays. It could store those as a bitmap or similar. – dan1st Jun 05 '21 at 22:16
  • 1
    Why are you using `uint64_t` when the objects in question are (to your knowledge) `uint8_t`? Seems like a recipe for failure of one sort or another. – JaMiT Jun 05 '21 at 22:36
  • 2
    I don't know if the immediate problem is related to strict aliasing, but you are poised to run afoul of [strict aliasing rules](https://stackoverflow.com/questions/2771023/c99-strict-aliasing-rules-in-c-gcc). – JaMiT Jun 05 '21 at 22:38

1 Answers1

2

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);
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93