Can a java module call a c module?

扶醉桌前 提交于 2020-01-02 08:12:42

问题


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


回答1:


yes you can use Java Native Interface to do this:




回答2:


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.




回答3:


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



回答4:


Look into JNI (Java Native Interface).




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/2082265/can-a-java-module-call-a-c-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!