Native interoperability | Java | C# |
---|---|---|
Cross-language interoperability | No (only with CORBA or JNI) | Yes; C# was designed for it |
External/native methods | Yes | Yes |
Marshalling | External glue code required | Yes; metadata controlled |
Pointers and arithmetics | No | Yes |
Native types | No | Yes |
Fixed-size buffers | No | Yes |
Explicit stack allocation | No | Yes |
Address-of | No | Yes |
Object pinning (fix variable to address) | No | Yes |
The Java Native Interface (JNI) feature allows Java programs to call non-Java code. However, JNI does require the code being called to follow several conventions and imposes restrictions on types and names used. This means that an extra adaption layer between legacy code and Java is often needed. This adaption code must be coded in a non-Java language, often C or C++. Java Native Access (JNA) allows easier calling of native code that only requires writing Java code, but comes at a performance cost.
In addition, third party libraries provide for Java-COM bridging, e.g. JACOB (free), and J-Integra for COM (proprietary).
.NET Platform Invoke (P/Invoke) offers the same capability by allowing calls from C# to what Microsoft refers to as unmanaged code. Through metadata attributes the programmer can control exactly how the parameters and results are marshalled, thus avoiding the need for extra adaption code. P/Invoke allows almost complete access to procedural APIs (such as Win32 or POSIX), but limited access to C++ class libraries.
In addition, .NET Framework also provides a .NET-COM bridge, allowing access to COM components as, if they were first-class .NET objects.
C# also allows the programmer to disable the normal type-checking and other safety features of the CLR, which then enables the use of pointer variables. When using this feature, the programmer must mark the code using the unsafe
keyword. JNI, P/Invoke, and "unsafe" code are equally risky features, exposing possible security holes and application instability. An advantage of unsafe, managed code over P/Invoke or JNI is that it allows the programmer to continue to work in the familiar C# environment to accomplish some tasks that otherwise would require calling out to unmanaged code. An assembly (program or library) using unsafe code must be compiled with a special switch and will be marked as such. This enables runtime environments to take special precautions before executing potentially harmful code.
Read more about this topic: Comparison Of C Sharp And Java, Language and Features
Famous quotes containing the word native:
“The Iliad represents no creed nor opinion, and we read it with a rare sense of freedom and irresponsibility, as if we trod on native ground, and were autochthones of the soil.”
—Henry David Thoreau (18171862)