jni使用--java native 調用c++ boost regex庫例子

編寫BoostRegexStrategy.java


package com;
public class BoostRegexStrategy {

	static{
		try{
			System.loadLibrary("boost_regex");
		}catch(UnsatisfiedLinkError e){
			//TODO
		}
						
	}

	public native boolean find(String text, String regex)throws Exception;

}

編寫用c/c++ native方法的實現

用javah生成c語言頭文件:

#/usr/jdk/bin/javah com.BoostRegexStrategy 

應該會生成com_BoostRegexStrategy.h文件

然後編寫對應的cpp文件BoostRegexStrategy.cpp來實現com_BoostRegexStrategy.h中申明的函數:
#include "com_BoostRegexStrategy.h"
#include <boost/regex.hpp>

bool find(const char* text, const char* regex)
{
 boost::regex reg(regex);
 return boost::regex_search(text, reg);
}


JNIEXPORT jboolean JNICALL Java_com_BoostRegexStrategy_find
 (JNIEnv * env, jobject obj, jstring jtext, jstring jregex)
{
  //從參數字符串取得指向字符串UTF-8的指針
  const char* text = env->GetStringUTFChars(jtext, JNI_FALSE);
  const char* regex = env->GetStringUTFChars(jregex, JNI_FALSE);

 bool matchResult = find(text, regex);
  
env->ReleaseStringUTFChars(jtext, text);
env->ReleaseStringUTFChars(jregex, regex);

return (jboolean)matchResult;

}



生成libboost_regex.so文件(動態鏈接庫)

#g++BoostRegexStrategy.cpp -I/usr/jdk/include/ -I/usr/jdk/include/linux -I/usr/local/include/boost -lboost_regex -fPIC-shared -o libboost_regex.so 

假設libboost_regex.so放在了$my_lib下面了

需要注意在我們的動態鏈接庫會用到boost regex庫,我這裏是libboost_regex.so.1.50.0
#cp  /usr/local/include/boost/libboost_regex.so.1.50.0 $my_lib

編寫junit測試用例TestCase.java(代碼略)

執行#export LD_LIBRARY_PATH=$my_lib:$LD_LIBRARY_PATH, 然後#java -cp ./:org.hamcrest.core.jar:junit.jar org.junit.runner.JUnitCore com.TestCase
或者
#java -Djava.library.path=$my_lib -cp ./:org.hamcrest.core.jar:junit.jar org.junit.runner.JUnitCore com.TestCase
再或者
把動態鏈接庫libboost_regex.so和libboost_regex.so.1.50.0放到/usr/lib/下(系統默認lib路徑),執行#java  -cp ./:org.hamcrest.core.jar:junit.jar org.junit.runner.JUnitCore com.TestCase

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章