简体   繁体   中英

How to compile Java native library?

I hope that's the right word to use, "compile." I'm asking here since I'm not even sure what to Google for to get more information.

I want to use this library here: http://jiggawatt.org/badc0de/android/#gifflen

The download gives a bunch of .cpp and .h files. From what I understand, I need a .so file in order to use System.loadLibrary(libName) .

What I can't figure out is how to compile these C++ files into the necessary .so file?

You can create shared object file using below mentioned command.

gcc -shared -fpic -o <so-file-name>.so a.c b.c

on Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

References:

C++ Dynamic Shared Library on Linux

Build .so file from .c file using gcc command line

Sample tutorial

Sample code to run .so file using java with commands:

HelloJNI.c

#include <jni.h>
#include <stdio.h>
#include "HelloJNI.h"

JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
   printf("Hello World!\n");
   return;
}

HelloJNI.java

public class HelloJNI {
   static {
      System.loadLibrary("hello"); // hello.dll (Windows) or libhello.so (Unixes)
   }
   // A native method that receives nothing and returns void
   private native void sayHello();

   public static void main(String[] args) {
      new HelloJNI().sayHello();  // invoke the native method
   }
}

Steps to run above .c file using .java file

javac HelloJNI

javah HelloJNI

gcc -shared -fpic -o libhello.so -I/usr/java/default/include -I/usr/java/default/include/linux HelloJNI.c

java  -Djava.library.path=. HelloJNI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM