开发者

Can a java module call a c module?

Just out of interest , is it possible to call a C module from a j开发者_如何学JAVAava module ? If so , how to do that ?


yes you can use Java Native Interface to do this:


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.


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

  • Java Native Interface: Programmer's Guide and Specification

You can also use SWIG for this purpose:

  • SWIG Tutorial


Look into JNI (Java Native Interface).


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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜