0

I'm provided a std::set<int> object that I need to convert/copy into a jintArray to return to an Android app. I tried the code below, but it seems to be crashing my app with only this as a clue:

Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x2 in tid 19975

I suspect it's the cast, but I'm not sure the right way to do it. theId is definitely an int. See the code below:

std::set<int> speciesSet = someFunctionThatReturnsASet();

speciesIDSet = env->NewIntArray(speciesSet.size());

int count = 0;
for ( std::set<int>::iterator itr=speciesSet.begin(); itr != speciesSet.end(); itr++ ) {
    try {
        int theId = *itr;
        // This is the last line of code that runs.
        env->SetIntArrayRegion(speciesIDSet, count, 1, (jint*)theId);
        count++;
    }
    catch (const std::exception& e) {
        std::cout << e.what();
    }
    catch (...) {
        std::cout << "oops";
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Darthg8r
  • 12,377
  • 15
  • 63
  • 100
  • 1
    You can't cast an int to a pointer of any kind. Doesn't it just work without the cast? Have a look here: https://stackoverflow.com/questions/1610045/how-to-return-an-array-from-jni-to-java – Jerry Jeremiah Jul 29 '19 at 21:40

2 Answers2

1

SetIntArrayRegion() expects an array as the source buffer. You are trying to pass it an "array" of 1 int at a time. Which is fine, but as another answer pointed out, you need to use (jint*)&theId instead of (jint*)theId to do that.

Another option would be to create an actual array first, then call SetIntArrayRegion() only 1 time to copy the entire array in one go:

std::set<int> speciesSet = someFunctionThatReturnsASet();

std::vector<int> speciesVec(speciesSet.begin(), speciesSet.end());

speciesIDSet = env->NewIntArray(speciesVec.size());
env->SetIntArrayRegion(speciesIDSet, 0, speciesVec.size(), reinterpret_cast<jint*>(speciesVec.data()));
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

I think, that you want to write (jint*)&theId instead of (jint*)theId.

The second one is saying, you want to interpret that number as jint* pointer. But you want jint* pointer to the number.

Přemysl Šťastný
  • 1,676
  • 2
  • 18
  • 39