android NDK 使用c++
今天简单写一下,如何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 函数体。
补充:移动开发 , Android ,