这是本机C++方法。

JNIEXPORT jboolean JNICALL Java_xpnp_XpNamedPipe_readBytes
(JNIEnv* pEnv, jclass cls, jlong pipeHandle, jbyteArray readBufferJava, jint bytestoread, jint timeoutMsecs){

    jbyte* readBuffer = NULL;
    try {
        readBuffer = pEnv->GetByteArrayElements(readBufferJava, NULL);
        if (readBuffer == NULL) {
            throw std::bad_alloc();
        }
        int retval = XPNP_readBytes ((XPNP_PipeHandle)pipeHandle, (char*)readBuffer, bytestoread, timeoutMsecs);

        std::cout<<"this is what I read: " << readBuffer << "\n";
        std::flush(std::cout);

        return (retval <= 0) ? 0 : retval;
    }catch (std::exception& except) {
        // setErrorInfo(except.what());
    }
    return 0;
}

此方法打印从调用readBuffer读取的XPNP_readBytes的正确文本,但是将全零的数组传递给Java!知道为什么会这样吗?在传递指针或将其转换为Java时,我做错什么了吗?

这是Java文件中本机C++方法的声明。
private static native boolean readBytes(long pipeHandle, byte[] buffer, int bytesToRead, int timeoutMsecs);

这就是我要调用本机方法的地方。
boolean b = readBytes(namedPipeHandle, buffer, bytesToRead, timeoutMsecs);
String a = new String(buffer);

我在调用后读取的buffer全为0,即使它在本机代码中显示正确的文本也是如此!

最佳答案

查找ReleaseByteArrayElements

10-04 14:25