[关闭]
@StarSky 2018-08-20T10:21:12.000000Z 字数 2627 阅读 594

2017-07-25 JNI (Java Native Interface) & singleton

工作日记


build

  1. package into a assigned path[1](jobject vs jclass)and build a .jar file[2]
  2. use cmake build a .dylib or .so file.[3]
  3. assign[4] or set the java.lib.path [5][6], and put the .dylib or .so in.
  4. use singleton[7] when load lib.
  5. edit CmakeList.txt add .h & .cpp as entrance

    ADD_LIBRARY(projectName SHARED include/jni/com_****_JNI.h src/jni/****JNI.cpp)

    @Q: when using on the linux service, the third method doesn't work, also the other[8], we should notice the difference between osx and linux[9].

    @Q: while cmake the project

    /export/home/aiusr/env/image/bin/ld:src/jni/libJNI.a(IdcardRecognizerController.cpp.o): relocation R_X86_64_32 against '.bss' can not be used when making a shared object; recompile with -fPIC
    

    error occured

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
    

    need to be modified to

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC ")
    

    It seems like linux enviroment is the main reason.

  1. public class JNIService {
  2. private static final JNIService instance = new JNIService();
  3. private JNIService(){
  4. try{
  5. System.out.println("----start-----");
  6. System.out.println(System.getProperty("java.library.path"));
  7. System.out.println("----end-----");
  8. System.loadLibrary("cppLib");
  9. }catch(Throwable e)
  10. {
  11. System.out.println("The cppLib don't load correctly");
  12. }
  13. }
  14. public static JNIService getInstance(){
  15. return instance;
  16. }
  17. //define a native function
  18. public native String function(int type, String filePath);
  19. public String callCpp(Map<String, Object> paramMap) throws Exception {
  20. String res = function(type, filePath);
  21. System.out.print("res is ------->>>>>>" + res);
  22. return res;
  23. }
  24. }

test

  1. because using of singleton, new the service will be illegal, so I used the JNIService.getInstance().
  1. public class TestJNI {
  2. private JNIService jNIService = JNIService.getInstance();
  3. @Test
  4. public void test(){
  5. Map<String,Object> paramMap = new HashMap<String,Object>();
  6. paramMap.put("type","front");
  7. paramMap.put("imgFilePath","/Users/saber/Downloads/test_img/51152119960731792x_1.jpeg");
  8. try {
  9. String res = JNIService.callCpp(paramMap);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注