a284628487 / JniSample

0 stars 0 forks source link

Demo 示例 #5

Open a284628487 opened 6 years ago

a284628487 commented 6 years ago

Cpp调用C

invoker.cpp

#include <jni.h>
#include <string>
#include "jcf.h"

namespace ccf {
    void whatS2(JNIEnv *env, jobject jthiz);
}
using namespace ccf;

extern "C" JNIEXPORT jstring

JNICALL
Java_com_example_hoperun1_MainActivity_stringFromJNI(
        JNIEnv *env, jobject thiz) {
    std::string hello = "Hello from C++";
    //
    // using namespace
    whatS2(env, thiz);
    // 
    // JNIJcf
    JNIJcf *j;
    jint grade = j->GetGrade(thiz);
    // end
    return env->NewStringUTF(hello.c_str());
}

如果在C中调用JNIJcf,则:

#include "jcf.h"
// ...

// JNIJcf
JNIJcf *jcf;
(*jcf)->GetGrade(jcf, jthiz);
// end

实现namespace方法

whatS2.cpp

#include "jni.h"

namespace ccf {

void whatS2(JNIEnv *env, jobject jthiz) {
    jintArray intArray = env->NewIntArray(2);
    jint buf[2];
    buf[0] = 1;
    buf[1] = 3;
    // this, jintArray array, jsize start, jsize len, const jint* buf
    env->SetIntArrayRegion(intArray, 0, 2, buf);
    // 从jintArray中获取数值并赋值给int数组
    env->GetIntArrayRegion(intArray, 0, 2, buf);
    // 从jintArray中获取数值并把数值以数组形式返回
    jint *newBuf = env->GetIntArrayElements(intArray, NULL);
    // 释放intArray
    env->ReleaseIntArrayElements(intArray, newBuf, 0);
}

}

定义C/C++适用函数

jcf.h

#include "jni.h"

#ifndef HOPERUN1_JCF_H
#define HOPERUN1_JCF_H

struct _JNIJcf;
typedef const struct JNIJcfInterface* C_JNIJcf;

#if defined(__cplusplus)
typedef _JNIJcf JNIJcf;
#else
typedef const struct JNIJcfInterface* JNIJcf;
#endif

struct JNIJcfInterface {
    jint (*GetGrade)(JNIJcf*, jobject);
};

struct _JNIJcf {
    const struct JNIJcfInterface* functions;

#if defined(__cplusplus)
    jint GetGrade(jobject obj) {
        return functions->GetGrade(this, obj);
    }
#endif

};

#endif //HOPERUN1_JCF_H
a284628487 commented 6 years ago
jint GetGrade(JNIJcf *jcf, jobject jobj) {
    return 27;
}

#if defined(__cplusplus)
JNIJcf* GetJcf() {
    struct _JNIJcf jcf;
    jcf.functions->GetGrade = GetGrade;
    return &jcf;
}
#else
JNIJcf* GetJcf() {
    struct JNIJcfInterface jcf;
    jcf.GetGrade = GetGrade;
    return (JNIJcf*)(&jcf);
}
#endif