jstring Java_com_example_hellojni_HelloJni_stringFromJNI

本文将介绍如何在Java应用中通过JNI接口与本地C/C++代码进行交互,实现跨平台通信的功能。通过一个简单的例子展示了如何在Java代码中调用本地库函数,并返回字符串结果。
package com.example.hellojni;

import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;


public class HelloJni extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        /* Create a TextView and set its content.
         * the text is retrieved by calling a native
         * function.
         */
        TextView  tv = new TextView(this);
        tv.setText( stringFromJNI() );
        setContentView(tv);
    }

    /* A native method that is implemented by the
     * 'hello-jni' native library, which is packaged
     * with this application.
     */
    public native String  stringFromJNI();

    /* This is another native method declaration that is *not*
     * implemented by 'hello-jni'. This is simply to show that
     * you can declare as many native methods in your Java code
     * as you want, their implementation is searched in the
     * currently loaded native libraries only the first time
     * you call them.
     *
     * Trying to call this function will result in a
     * java.lang.UnsatisfiedLinkError exception !
     */
    public native String  unimplementedStringFromJNI();

    /* this is used to load the 'hello-jni' library on application
     * startup. The library has already been unpacked into
     * /data/data/com.example.hellojni/lib/libhello-jni.so at
     * installation time by the package manager.
     */
    static {
        System.loadLibrary("hello-jni");
    }
}
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <string.h>
#include <jni.h>

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
 */
jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    return (*env)->NewStringUTF(env, "Hello from JNI !");
}

# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
LOCAL_PATH := $(call my-dir)


include $(CLEAR_VARS)


LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.c


include $(BUILD_SHARED_LIBRARY)
### Java JNI 示例:`MainActivity` 中 `stringFromJNI` 方法实现及调用过程 在 Android 应用开发中,Java Native Interface (JNI) 提供了一种机制让 Java 和 C/C++ 代码能够相互协作。为了展示如何利用 JNI 实现 Java 和本地代码之间的交互,下面将介绍一个具体的例子——在 `MainActivity.java` 文件里定义了一个名为 `stringFromJNI()` 的函数来获取来自原生库的消息。 #### 创建 Java 类中的声明部分 首先,在项目的主活动中声明两个静态变量用于加载共享库以及对外提供接口的方法: ```java public class MainActivity extends AppCompatActivity { static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.sample_text); tv.setText(stringFromJNI()); } // 声明要由本地代码实现的公共成员方法 public native String stringFromJNI(); } ``` 这段代码展示了如何在一个 Activity 内部引入外部编写的动态链接库,并通过关键字 `native` 来标记那些将在其他地方被实际编码执行的功能[^1]。 #### 编写对应的 C 或者 C++ 函数 接着需要编写相应的 C 或者 C++ 源文件(通常命名为 `.cpp`),其中包含了上述提到的 `stringFromJNI` 函数的具体逻辑。这里给出的是基于 C++ 版本的例子: ```cpp #include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_com_example_myapplication_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } ``` 此段程序实现了当应用程序请求访问该字符串资源时所应返回的内容。注意这里的命名约定遵循了特定模式以便于 JVM 正确识别它作为目标对象上的指定实例方法的一部分[^2]。 #### 构建与调试 完成以上两步之后就可以按照常规流程打包 APK 并安装至设备上测试效果了。如果一切顺利的话,则会在界面上看到预期的文字输出:“Hello from C++”。 #### 关联问题处理 对于更复杂的需求场景下可能还需要考虑更多因素,比如异常捕获、线程同步等问题;另外值得注意的一点是在某些情况下直接传递简单数据结构并不能完全解决问题,这时就需要借助 JNI 接口进一步操作 Java 对象或数组等高级特性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值