Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ library in java

I am new to this forum, so please excuse me if i cannot put my question in a right way.

I want help in using a C++(.lib and.h) files in java.
I want to use methods of that .lib file in my java code .

Prototype of function is like :

FunctionXYZ(BYTE *Data1, BYTE *Data2, BYTE *Data3, int Data4);

Environment i would be using is centOS.

Thank you in advance

P.S: I do not have source code for this .lib

like image 364
satishsingh2230 Avatar asked Jul 07 '14 10:07

satishsingh2230


People also ask

Can I use C with Java?

Java native interface (JNI) is a framework provided by java that enables java programs to call native code and vice-versa. Using JNI a java program has the capability to call the native C code.

What does C do in Java?

C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system. Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine).

Is it possible to call C and C++ functions in Java?

C/C++ and Java are popular programming languages. The Java Native Interface (JNI) is a standard to integrate in a portable way C++ and Java code. JNI works both way i.e. C++ implementation can be called from JAVA and vice versa.


2 Answers

To use functions from a .lib, you have to create JNI wrapper functions for these library functions, and then link them together with your library into a .dll.

Example:

  1. Assuming you have a function in your C++ library headers with this signature:

    int example(int a, int b);
    
  2. Create a function wrapper in C++:

    JNIEXPORT jint JNICALL Java_MyClass_example (JNIEnv* env, jobject obj, jint a, jint b) {
        return (jint) example(a, b);
    }
    
  3. Link the library and the wrapper into a DLL

  4. Create a Java class with the native method:

    public class MyClass {
        public native int example(int a, int b);
    }
    
  5. Load the DLL using the System.loadLibrary function (or similar)

  6. Now you can call the example method on an object of MyClass
like image 176
maxdev Avatar answered Sep 19 '22 11:09

maxdev


you can use JNI technology which enables you to interoperate with native code

please refer to this http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

like image 42
Yamen Ajjour Avatar answered Sep 16 '22 11:09

Yamen Ajjour