пʼятниця, 16 січня 2026 р.

 # Interaction Between Java and C/C++


6 min. reading


December 12, 2017


[

0

](https://devzone.org.ua/votes/show/post/38895)


· 74 ·


[

0

](#comments)


·


Java, despite some "drawbacks", is a powerful and, most importantly, in most cases, self-sufficient programming language. By self-sufficiency, I mean the ability to write programs that solve a specific task without involving other programming languages.


However, I deliberately noted that the self-sufficiency of the Java language manifests itself in most cases. Sometimes it is impossible to write a program completely without using auxiliary tools. For example, it may be necessary to use code that provides low-level access to the "hardware" of the computer on which the program is running. In the Java programming language, which is cross-platform by design, means for low-level access to the hardware part are not provided.


To solve this problem, Java developers included in the language the ability to call from Java programs programs implemented in other programming languages through native methods. The Java subsystem that implements this capability is called **JNI** (Java Native Interface – Java language interface that allows access to native methods).


Not long ago, I had to work with a Java library. The problem was that I needed to use methods under GPU (write in the comments if you would like several articles on the CUDA topic), but in the Java implementation of this library such functionality was not available, and I had to call methods from a C program. In this article, we will talk about the practical application of JNI.


## **Class Creation**


First, we need to create some class that will contain a native method.


```

public class HelloJNI {

   static {

      System.loadLibrary("hello"); // Loading library hello.dll

   }

   // Declaration of native method sayHello(), which takes no arguments and returns void 

   private native void sayHello();

   public static void main(String[] args) {

      new HelloJNI().sayHello();  // calling native method

   }

}

```


We declared the `HelloJNI` class, which contains the native method `sayHello`. Let's look at the code a bit.


The `static` block means that our library will be loaded during class loading. To allow the program to find the library – you need to add its path to the `classpath`. This can be done when running the program by adding the argument `-Djava.library.path=PATH_LIB`. There is also another option: instead of the `loadLibrary` method, use `load`. But in this case, you need to specify the full path to the library (including the `dll` or `so` extension).


We have a class, but it is not yet connected in any way with our library (we just don’t have the library yet).


## **Library Creation**


The next step is to compile the file and create the `h` file.


```

javac HelloJNI.java

javah HelloJNI

```


After which we get the following header file:


```

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class HelloJNI */

 

#ifndef _Included_HelloJNI

#define _Included_HelloJNI

#ifdef __cplusplus

extern "C" {

#endif

/*

 * Class:     HelloJNI

 * Method:    sayHello

 * Signature: ()V

 */

JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *, jobject);

 

#ifdef __cplusplus

}

#endif

#endif

```


What can we learn by looking at this file? First, that the C program code will include the `jni.h` file, which, by the way, contains all the necessary functions for working with JNI. Second, we will see that the method that in the `HelloJNI` class was described as


```

private native void sayHello();

```


in the C program is described slightly differently, namely:


```

JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *, jobject);

```


As we can see, the function takes two arguments, although we did not specify them. What are these?


* `JNIEnv*` – a pointer to the JNI environment, which gives you access to all JNI functions;

* `jobject` – a pointer to the `this` object in Java.


The definition of `JNIEXPORT` in the `jni_md.h` file, which is called from `jni.h`, is described as follows:


```

#define JNIEXPORT __declspec(dllexport)

```


In the same file, the definition of `JNICALL` is described as:


```

#define JNICALL __stdcall

```


After this, it becomes clear that all these "scary" descriptions are just notations used when calling a regular exported function.


## **Implementation in C**


Now we need to implement the described function in a `c` file.


```

#include <jni.h>

#include <stdio.h>

#include "HelloJNI.h"

 

JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {

   printf("Hello World!\

");

   return;

}

```


As we can see, the function outputs a line to the console and returns `void`. *Here, the main thing is not to forget to connect the header file we created earlier.* The `jni.h` file is located in the directories `JAVA_HOME\\include` and `JAVA_HOME\\include\\win32`.


Finally, we can compile the file:


```

gcc -Wl --add-stdcall-alias -I"%JAVA_HOME%\\include" -I"%JAVA_HOME%\\include\\win32" -shared -o hello.dll HelloJNI.c

```


I’ll explain a few parameters:


* `-Wl --add-stdcall-alias` – an option that prevents the occurrence of a linker error (`UnsatisfiedLinkError`);

* `-I` – additional libraries for inclusion (in our case, to include the `jni.h` file);

* `-shared` – to generate a dynamic library;

* `-o` – specifies the output file name.


Now we can run the Java program:


```

java HelloJNI

Hello World!

```


*Remember, if you used the `loadLibrary` method to load the library, you need to run the program like this:*


```

java -Djava.library.path=PATH_TO_LIB HelloJNI

Hello World!

```


## **Conclusion**


In the article, I described the general concepts of how JNI can be used. Using this technology, you can also call class methods, create new objects, pass various parameters (arrays, strings, etc.), return various values, and much more. You can read more about it [here](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/) and [here](https://www.javamex.com/tutorials/jni/getting_started.shtml).


Using native methods in the Java language violates the principle of cross-platform nature of the Java language. A program that uses a DLL becomes highly dependent on the platform on which the DLL is implemented. The use of native methods can be used in cases where the main program (Java) is expected to run on different platforms, while the programs in the form of native methods are planned to be developed for each specific platform. If a Java program that uses native methods is planned to be used only on the platform on which the native methods are implemented, then why the cross-platform nature at all?


Another drawback is that from a native method you can gain access to any part of the system, which contradicts the Java methodology (one of the requirements for Java is the security requirement).


However, despite the drawbacks – the programmer himself chooses which technologies to use.


Noticed an error? Report it to the author, just highlight the text with the error and press Ctrl+Enter


[

Subscribe

](https://devzone.org.ua/login)


##### Codeguida  24


Joined:

    2 years ago


##### Comments (0)


#### There are no comments yet


To leave a comment, you need to log in.


Login


#### Similar articles


1) 


[

Python vs C. Comparison of ctypes and Python/C API

](https://devzone.org.ua/post/python-vs-c-porivniannia-ctypes-i-pythonc-api)


            There may be many reasons to use C code in the Python interpreter,...

        

2) 


[

Smart pointers in C

](https://devzone.org.ua/post/rozumni-vkazivnyky-u-c)


            I am a passionate supporter of C, but sometimes I lack certain high-level features...

        

3) 


[

My first impressions of C++

](https://devzone.org.ua/post/moyi-pershi-vrazennia-vid-c)


            I have been professionally involved in web development for about fifteen years, mostly in...

        

4) 


[

Basics of AVR C Programming

](https://devzone.org.ua/post/osnovy-prohramuvannia-avr-c)


            This article discusses some key concepts of programming in C for microcontrollers...

        

5) 


[

Why I hate using auto in C++

](https://devzone.org.ua/post/chomu-ia-nenavydzu-vykorystannia-auto-u-c)


            I don’t know about other programmers, but when reading code, I try to focus...

        

6) 


[

What are synchronous and asynchronous callbacks in C#?

](https://devzone.org.ua/post/shcho-take-synkhronnyy-ta-asynkhronnyy-kolbek-u-c)


            This article will help you understand synchronous and asynchronous callbacks in C# and their purpose...

        

7) 


[

Limiting concurrent threads in C#

](https://devzone.org.ua/post/obmezennia-odnochasnykh-potokiv-v-c)


            This is a translation of the post Constraining Concurrent Threads in C# by Mark Heath - Microsoft...

        

8) 


[

C++20 standard officially approved

](https://devzone.org.ua/post/standart-c20-ofitsiyno-zatverdyly)


            The ISO committee recently approved the C++20 standard draft. The main language standard in...

Немає коментарів:

Дописати коментар

Pure Acetone: "Pin Tweet to IPFS https://chro…" - Mastodon
https://mastodon.social/deck/@pureacetone/111421706607809813

 Французская журналистка марокканского происхождения Нора Бюссиньи на год ушла в подполье, внедрившись под прикрытием в левые и пропалестинс...