tags:

views:

196

answers:

6

Just out of interest , is it possible to call a C module from a java module ? If so , how to do that ?

+4  A: 

yes you can use Java Native Interface to do this:

Aly
+1  A: 

Look into JNI (Java Native Interface).

+3  A: 

Yes, you call C/C++ from Java using the Java Native Interface (JNI) from this purpose.

You can also use SWIG for this purpose:

Miguel Sevilla
+1  A: 

Yes. As others have already mentioned, JNI or Java Native Interface is Sun's preferred way of doing this. If you feel you'll need to call the C code from other languages as well as Java, I'd look into SWIG, which will transparently generate the JNI code for you, but also allow you to do similar things with, for example, Python.

Chinmay Kanchi
+2  A: 

Yes, you can do it. Whether you should do it is another matter.

On the pro side:

  • Calling C libraries from Java will avoid the need to recode the libraries in Java (but see below).

  • For some computational intensive algorithms, a well-written C implementation may be faster than an equivalently well-written Java version.

  • Some operating system specific operations cannot be implemented in pure Java.

On the con side:

  • There is a greater overhead in making a JNI call versus a simple Java method call.

  • If your C library is not thread-safe, you have to be really careful calling it from Java. And as a rule, C libraries are not implemented with thread safety in mind.

  • If your C library has memory management issues, it may destabilize the Java platform resulting in JVM crashes.

  • Calling native libraries immediately means that your application is harder to port, and requires a more complicated build process.

Stephen C
A: 

There are a number of C to (Java) bytecode compilers, which may be able to turn your C code into a .jar of portable Java classes you can call directly from Java.

Detriments versus JNI:

  • There is a noticeable performance penalty, typically at least 100%.

Benefits versus JNI:

  • Just like running pure Java code, it is safe, does not require special privileges to load, and does not require recompiling for every target platform.

(When I say "JNI" I really mean all Java interfaces to native code. For example, the same applies to CNI.)

ephemient
Another detriment versus JNI is that you won't be able to do platform specific things this way ... and that's (IMO) the most important use-case for C libraries.
Stephen C