Android NDKはc++を使用

1756 ワード

今日简単に书いて、どのようにandroid NDKはどのように1つのC++クラスの中の関数を呼び出します
//#include <iostream>​
#include <stdio.h>
#include <pthread.h>
#include <jni.h>
#include <android/log.h>
//#include "testport.h"
​

static const char *TAG="Acanoe";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO,  TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
extern "C" {


using namespace std;


extern pthread_cond_t ntcond;
extern pthread_mutex_t ntmutex;


class TestPort{
public:
 explicit TestPort();
 ~TestPort();


 static void *thr_fn(void *arg);
 void InitPort();


private:
 pthread_t ntid;
};


pthread_cond_t ntcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t ntmutex = PTHREAD_MUTEX_INITIALIZER;


TestPort::TestPort(void){


}


TestPort::~TestPort(void){


}


void TestPort::InitPort()
{
 pthread_create(&ntid, NULL, thr_fn, NULL);
}


void* TestPort::thr_fn(void *arg)
{
 LOGD("thread_create success");
 pthread_mutex_lock(&ntmutex);
 pthread_cond_signal(&ntcond);
 pthread_mutex_unlock(&ntmutex);
}


}
extern "C" {
 jint Java_com_example_pthread_Ptrhead_cjjtest (JNIEnv *env, jclass thiz);
};


jint Java_com_example_pthread_Ptrhead_cjjtest
(JNIEnv *env, jclass thiz)
{
 LOGD("cjjtest start");
 TestPort test;
 test.InitPort();
 pthread_mutex_lock(&ntmutex);
 pthread_cond_wait(&ntcond, &ntmutex);
 pthread_mutex_unlock(&ntmutex);
 LOGD("got the signal.
"); }

簡単に説明します.
実はC++を使って
extern "C"{
}
C関数はC++関数を呼び出すことができて、それからあなたの本当のJni関数体です.