3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android NDK で C++ から java の呼び出し

Last updated at Posted at 2018-04-23

概要

Visual Studio 2017の**OpenGLES アプリケーション(Android, iOS)**で、C++からJavaを呼び出すメモ

環境

  • Visual Studio 2017
  • Visual C++ > クロスプラットフォーム > OpenGLES アプリケーション(Android, iOS)
  • android-21

内容

既存クラスの場合

auto env = state->activity->env;
auto vm = state->activity->vm;

vm->AttachCurrentThread(&env, NULL);

jstring str = env->NewStringUTF("abc");

jclass     cls = env->FindClass("java/lang/String");
jmethodID  mid = env->GetMethodID(cls, "toCharArray", "()[C");
jcharArray ary = (jcharArray)env->CallObjectMethod(str, mid);

vm->DetachCurrentThread();

ユーザークラスの場合

[プロジェクト名].Packagingプロジェクトのsrcフォルダ以下にjavaのソースを追加

Test.java
package com.test;

public class Test
{
    public boolean test()
    {
        return true;
    }
}

AndroidManifest.xmlのapplication:android:hasCodeをtrueに

AndroidManifest.xml
<application android:label="@string/app_name" android:hasCode="true">

NativeActivity:getClassLoaderを使って呼び出す

https://stackoverflow.com/questions/14586821/android-flurry-integration-with-ndk-app
http://archive.is/QzA8#selection-471.0-507.81

auto env = state->activity->env;
auto vm = state->activity->vm;

vm->AttachCurrentThread(&env, NULL);

jclass activityClass = env->FindClass("android/app/NativeActivity");
jmethodID getClassLoader = env->GetMethodID(activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
jobject classLoaderInstance = env->CallObjectMethod(state->activity->clazz, getClassLoader);
jclass classLoader = env->FindClass("java/lang/ClassLoader");
jmethodID findClass = env->GetMethodID(classLoader, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring strClassName = env->NewStringUTF("com/test/Test");
jclass classIWant = (jclass)env->CallObjectMethod(classLoaderInstance, findClass, strClassName);
jmethodID testMethod = env->GetStaticMethodID(classIWant, "test", "()Z");
jboolean retValue = env->CallStaticBooleanMethod(classIWant, testMethod);

vm->DetachCurrentThread();
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?