将标准:设置为<int> jintArray

Convert std:set<int> into jintArray

本文关键字:int gt jintArray 标准 lt 设置      更新时间:2023-10-16

我提供了一个std::set<int>对象,我需要转换/复制到jintArray中以返回到Android应用。我尝试了下面的代码,但是它似乎只是用它作为线索崩溃了:

致命信号11(sigsegv(,代码1(segv_maperr(,故障addr 0x2 19975

我怀疑这是演员,但我不确定正确的方法。theId绝对是int。请参阅下面的代码:

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";
    }
}

SetIntArrayRegion()期望数组作为源缓冲区。您正在尝试一次将其传递为1 int的"数组"。很好,但是正如另一个答案所指出的那样,您需要使用(jint*)&theId而不是(jint*)theId来做到这一点。

另一个选项是首先创建一个实际数组,然后仅调用SetIntArrayRegion()一次复制整个数组:

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

我想,您想编写(jint*)&theId而不是(jint*)theId

第二个说,您想将该数字解释为Jint*指针。但是您想要jint*指向数字。