这是本机 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
从 call 读取的正确文本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,即使它在本机代码中打印了正确的文本!