今天簡單寫一下,如何android NDK 如何調用一個C++ 類裡面的函數
[cpp] view plaincopyprint?//#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.\n");
}
//#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.\n");
}
簡單解析一下:
其實就是把 C++ 使用
extern "C" {
}
的方式使得 C 函數可以調用C++ 函數,然後才是你真正的 Jni 函數體。