android开发: 在C++代码里打印jstring 怎么写
在C++代码中打印jstring,可以使用JNIEnv接口的GetStringUTFChars函数将jstring转换为C字符串,然后使用常规的C++输出函数打印。
下面是一个示例代码:
#include <jni.h>
#include <iostream>
extern "C" JNIEXPORT void JNICALL
Java_com_example_myapplication_MainActivity_printString(JNIEnv* env, jobject, jstring jstr) {
// 将jstring转换为C字符串
const char* cstr = env->GetStringUTFChars(jstr, NULL);
// 打印C字符串
std::cout << cstr << std::endl;
// 释放转换后的C字符串
env->ReleaseStringUTFChars(jstr, cstr);
}
在上面的示例中,我们定义了一个名为printString的JNI函数,它接受一个jstring参数,并将其转换为C字符串后打印出来。请确保将Java_com_example_myapplication_MainActivity_printString替换为您实际的JNI函数名。
请注意,在使用完cstr后,需要通过ReleaseStringUTFChars函数释放资源,以避免内存泄漏
原文地址: https://www.cveoy.top/t/topic/irYg 著作权归作者所有。请勿转载和采集!