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

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