Skip to content

IanDarwin/javaevolved-java_callling_c

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Calling C Code from Java

Java has almost always had the ability to reach outside the JVM to run code written in other languages. Java 1.1 introduced JNI, the Java Native Interface. Along the way the JVM itself was extended with an invoke machine instruction for running non-java code like Jython (Java Python), JRuby, and others. In its roaring twenties (i.e., Java 22), our favorite language gained the Foreign Function and Memory API, a simpler way of directly invoking compiled code such as that from C.

With JNI (as shown in the oldway subdirectory) you simply declare your method as native, but then you have to run javac -h to generate a C-language .h (header) file, then have your C code interface with the slightly cumbersome JNI C-language API.

FFM, shown in the newway folder, simplifies the C code to the point that it doesn’t have to know anything about Java. This makes it much easier to interface with existing C/C++-language libraries. It does take a few more lines of Java code, but the net effect is more readable and more maintainable. Compare the C code in both versions and you’ll see the difference!

Running the demo

Calling anything foreign to the JVM requires a bit of knowledge about your JDK and your system. You must be able to use *Nix-style development tools, be able to locate include files, and edit Makefiles using something other than a word processor.

To run it:

  • Make sure your system has an up-to-date JDK, the C compiler used to build your JDK, and the make build tool. This was built and tested using Java 25; you need Java 22 as a bare minimum for FFM. In a pinch you can do without make if you are handy with command-line invocations; just do what make would do.

  • If you want to run the oldway version, find where the JNI include files are on your system, and update the INCLUDES line in oldway/Makefile.

  • Then just do make run in the top level, or in either subdirectory to run just that one.

About

Example for javaevolved website of Java calling into C code, old and new ways.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors