jni技术 java代码调用c++代码返回字符串

java代码

public class DemoActivity extends Activity {


static{
System.loadLibrary("Hello");
}
public native String hello_from_c();
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, hello_from_c(), 0).show();
    }
}


使用javah工具快速生成(在JAVA代码中声明native方法的文件)生成头文件

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_itcast_ndk2_DemoActivity */


#ifndef _Included_cn_itcast_ndk2_DemoActivity
#define _Included_cn_itcast_ndk2_DemoActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     cn_itcast_ndk2_DemoActivity
 * Method:    hello_from_c
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_cn_itcast_ndk2_DemoActivity_hello_1from_1c
  (JNIEnv *, jobject);


#ifdef __cplusplus
}
#endif
#endif


c++代码

#include <stdio.h>

#include "cn_itcast_ndk2_DemoActivity.h"
#include <android/log.h>
#define LOG_TAG "System.out"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)


JNIEXPORT jstring JNICALL Java_cn_itcast_ndk2_DemoActivity_hello_1from_1c
  (JNIEnv * env, jobject ){
LOGD("begin");
// intt a;
//定义一个字符串的常量 (不能被修改的变量)
// const char* str1 = "hello";
// LOGD("INIT STR1");
// const char* str2 = "zhang san";
// LOGD("init str2");
// LOGD("str1=%s",str1);
// LOGD("str2=%s",str2);




// c代码不允许修改一个字符串的常量
// strcat(str1,str2);
// LOGD("strcat");
char* str = "你好 ,中国";

// return (**env).NewStringUTF(env, str);

//jni.h文件对c++对一些方法做了一些包装所以不需要*这个标记了

return (env)->NewStringUTF( str);


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值