Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run C source code from Java?

Tags:

java

c

Now I have some C source codes, I would like to use it in my java application. I need to execute the C source code, and get back the result to my java application. Instead of re-write all the C source code to java, how can I reuse the C's source code in my java application?

like image 416
DNB5brims Avatar asked Oct 23 '11 10:10

DNB5brims


4 Answers

Take a look at Java Native Interface.

The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call and to be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

like image 179
Aurelio De Rosa Avatar answered Oct 06 '22 12:10

Aurelio De Rosa


There are the following ways.

  1. JNI (see answer of @AurelioDeRosa +1)
  2. JNA
  3. If your C program can run as command line utility why not just to execute it using Runtime.getRuntime().exec() or ProcessBuilder?
like image 45
AlexR Avatar answered Oct 06 '22 13:10

AlexR


Two options:

  1. Make a library accessible via JNI or JNA
  2. Make an executable, and call it with ProcessBuilder or Runtime.exec and capture the output streem if needed
like image 37
Maurice Perry Avatar answered Oct 06 '22 13:10

Maurice Perry


Yes its possible Take a look at

Calling C Code from Java

like image 27
bilash.saha Avatar answered Oct 06 '22 13:10

bilash.saha