温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中怎么调用C的函数

发布时间:2021-06-24 15:56:26 来源:亿速云 阅读:386 作者:Leah 栏目:大数据

Android中怎么调用C的函数,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">
   <TextView        android:id="@+id/sample_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />
   <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="测试按钮"        android:id="@+id/btncs"        android:onClick="btnclick"/></android.support.constraint.ConstraintLayout>

按钮里面加上了onCLick的事件名称为btnclick,我们通过Alt+Enter选择在对应的Activity中创建这个按钮事件。

Android中怎么调用C的函数

MainActivity.java

我们回到MainActivity中,其中原来默认的stringFromJni方法就是直接返回了一个字符串,到时候我们看一下源码即可。

接下来我们来试一下带参数的方法怎么实现。

我们新建了一个settextgood的方法,里面有一个输入参数,和一个返回参数。

Android中怎么调用C的函数

可以看到,刚定义完的方法显示为红色字体,接下来我们鼠标放到方法名上,然后按ALT+ENTER,选择下方红框中的第一项

Android中怎么调用C的函数

程序会自动跳转到native-lib.cpp的文件夹中创建了对应的调用方法

Android中怎么调用C的函数

接下来我们编写这个settextgood的方法


extern "C"JNIEXPORT jstring JNICALLJava_dem_vac_vaccaendk_MainActivity_settextgood(JNIEnv *env, jobject instance, jstring str_) {    const char *str = env->GetStringUTFChars(str_, 0);
   //定义追加的字符    char * addstr=",我是追加的字符";    //定义要输出的字符并设置长度    char * outputstr = new char[strlen(str)+strlen(addstr)];    //开始组装输出的字符    //1.传入的字符拷贝进来    strcpy(outputstr,str);    //2.连接刚刚定义的追加字符    strcat(outputstr,addstr);
   //释放资源    env->ReleaseStringUTFChars(str_, str);
   return env->NewStringUTF(outputstr);}

最后我们再重新写了一按钮事件,点击进传入一个“Hello”进去。

Android中怎么调用C的函数

我们运行一下程序看看

Android中怎么调用C的函数

刚进来时显示Hello from C++,我们现在再点击一下测试按钮后看看结果

Android中怎么调用C的函数

看完上述内容,你们掌握 Android中怎么调用C的函数的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI