【问题标题】:Data through JNI is not passing properly通过 JNI 的数据未正确传递
【发布时间】:2015-01-28 05:19:39
【问题描述】:

我正在使用 JNI 调用原生 C++ 层。

java层

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++ 层中打印该值时,我可以看到它只打印整个字符串的第一个字符。

假设如果 audioFilePath 我像 "c:\test.wav" 一样传递,我只会像 c

那样在 c++ 层中打印

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

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

【问题讨论】:

  • 为什么有android标签? char 也是 1 个字节,unicode 需要 2 个字节 ...

标签: java android c++ c java-native-interface


【解决方案1】:

根据JNI docs GetStringCharsjchar * 中返回给定字符串的unicode 字符,unsigned short *。您将其转换为char *。当您将coutchar * 一起使用时,它需要一个带有空终止符的ASCII 格式的字符串。您将一个指向 unicode 格式字符串的指针传递给它,该字符串每隔一个字符 0 表示纯 ASCII 字符。因此,为什么只打印字符串中的第一个字符。

【讨论】:

    【解决方案2】:

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

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

    相反,试试

    GetStringUTFChars
    

    这也将被空终止。

    【讨论】:

    • 感谢使用 GetStringUTFChars 为我返回了正确的结果。
    • 别忘了让答案正确,这是最有用的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多