通过 JNI 的数据未正确传递

Data through JNI is not passing properly

本文关键字:JNI 数据 通过      更新时间:2023-10-16

我正在使用JNI来调用本机C++层。

爪哇层

int res= recog(audioFilePath, grammarFilePath, contextID, subContextID);

C++层

JNIEXPORT void JNICALL Java_com_uniphore_voice_recogniser_NuanceOfflineRecogniser_recog(JNIEnv *jenv, jobject jobj, jstring jaudioFilePath, 
                           jstring jgrammarFilePath, <br/>
                           jstring jcontextID, 
                           jstring jsubContext)
{
const char* _audioFilePath      = (char*)jenv->GetStringChars(jaudioFilePath, JNI_FALSE);
const char* _grammarFilePath    = (char*)jenv->GetStringChars(jgrammarFilePath, JNI_FALSE);
const char* _contextId          = (char*)jenv->GetStringChars(jcontextID, JNI_FALSE);
const char* _subContextId       = (char*)jenv->GetStringChars(jsubContext, JNI_FALSE);
std::wcout  << "audio file path: "  << _audioFilePath   <<" "<< std::strlen(_audioFilePath) <<std::endl
            << "grammar file path: "<< _grammarFilePath <<" "<<std::strlen(_grammarFilePath) << std::endl
            << "contextId: "        << _contextId       << std::endl
            << "subContextId: "     << _subContextId    << std::endl << std::endl;

我可以看到java层的值被正确传递到较低级别,但是在c ++层中,在C++层中打印该值时,我可以看到它只打印整个字符串的第一个字符。

假设如果我像"c:\test.wav"一样传递音频文件路径,我只像 c 一样在 c++ 层中打印

我正在尝试Visual Studio 2013和项目字符支持,我选择作为Unicode支持。

我是 c++ 环境的新手,请帮助了解这个环境的原因。

根据 JNI 文档GetStringChars返回给定字符串的 unicode 字符,这是一个unsigned short * jchar *。你把它投射到一个char *.当您将 coutchar * 一起使用时,它需要一个带有空终止符的 ASCII 格式的字符串。您可以向它传递一个指向 unicode 格式字符串的指针,该字符串具有纯 ASCII 字符的所有其他字符0。因此,为什么只打印字符串中的第一个字符。

GetStringChars 不返回指向单字节字符的指针,而是返回两个字节的 unicode 字符

const jchar * GetStringChars(JNIEnv *env, jstring string,
jboolean *isCopy);
Returns a pointer to the array of Unicode characters of the string.

相反,请尝试

GetStringUTFChars

这也将以空终止。