这是本机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,即使它在本机代码中打印出正确的文本!
答案 0 :(得分:1)
查找ReleaseByteArrayElements
。