C# calls Java classes and methods (IKVM / JNI-JNA bridge)
1. Prerequisites
-
Environmental Requirements:
-
IKVM: Install the IKVM toolkit (including
ikvmc
、ikvm
and other tools), requiring JDK and .NET Framework. -
JNI/JNA: Requires Java JDK (including
javac
、javah
) and .NET P/Invoke support.
-
IKVM: Install the IKVM toolkit (including
-
Document preparation:
- Java JAR package (such as
)。
- The complete definition of Java classes (need to expose the target class and methods).
- Java JAR package (such as
2. Method 1: Use IKVM bridge
principle: Convert Java bytecode to .NET assembly (DLL) and reference directly in C#.
Implementation steps:
-
Install IKVM:
- downloadIKVM binary packageAnd decompress and configure environment variables.
- Convert JAR to .NET DLL:
ikvmc -target:library -out:
- Reference DLL in C#:
using ; using ; // Corresponding to Java package name public class Program { public static void Main() { // Call Java class ExampleClass obj = new ExampleClass(); ("Hello from C#"); } }
Notes:
- Make sure that Java classes and methods are
public
of. - Some Java features (such as dynamic proxy) may be lost during the conversion process.
3. Method 2: Use JNI/JNA bridge
principle: Calling the Java virtual machine (JVM) through JNI, and C# calls the JNI interface through P/Invoke.
Implementation steps:
- Writing Java Local Interface (JNI):
public class NativeBridge { public static native void callFromCSharp(String message); }
- Generate C/C++ header file:
javac javah -jni NativeBridge
- Generate
。
- Implementing C/C++ bridge layer:
#include <> #include "" JNIEXPORT void JNICALL Java_NativeBridge_callFromCSharp(JNIEnv *env, jclass cls, jstring msg) { const char *cMsg = env->GetStringUTFChars(msg, 0); printf("Java received: %s\n", cMsg); env->ReleaseStringUTFChars(msg, cMsg); }
- Compile as DLL:
gcc -shared -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -o
- C# Call DLL:
using System; using ; public class Program { [DllImport("")] private static extern void Java_NativeBridge_callFromCSharp(string message); public static void Main() { Java_NativeBridge_callFromCSharp("Hello via JNI"); } }
Notes:
- Need to manually manage the JVM lifecycle (
JNI_CreateJavaVM
)。 - Cross-platform DLL/SO needs to be recompiled.
4. Frequently Asked Questions
-
IKVM conversion failed:
- When the dependency JAR package is missing, you need to add
-reference:
。
- When the dependency JAR package is missing, you need to add
-
JNI memory leak:
- use
ReleaseStringUTFChars
Free resources.
- use
-
DLL path issues:
- Make sure the DLL is in the output directory or
PATH
In environment variables.
- Make sure the DLL is in the output directory or
V. Advanced Features
- IKVM dynamic class loading:
var classLoader = new (typeof(Program).Assembly); var clazz = ("");
-
JNI callback C# method:
- Define a callback function in the C/C++ layer and call the C# delegation through P/Invoke.
Java calls DLL classes and methods (JNA)
1. Prerequisites
-
Environmental Requirements:
- Java 8+, installationJNA Library。
-
Document preparation:
- Target DLL (such as
) and its function signatures.
- Target DLL (such as
2. Use the JNA method
principle: Directly map DLL functions to Java interfaces through the JNA library, without writing C code.
Implementation steps:
- Add JNA dependencies:
<!-- Maven --> <dependency> <groupId></groupId> <artifactId>jna</artifactId> <version>5.13.0</version> </dependency>
- Define Java interface:
import ; import ; public interface NativeLib extends Library { NativeLib INSTANCE = ("NativeLib", ); // Map DLL functions void exampleFunction(String message); int addNumbers(int a, int b); }
- Calling DLL functions:
public class Main { public static void main(String[] args) { ("Hello from Java"); int sum = (3, 4); ("Sum: " + sum); } }
Notes:
- The function name and parameter type must strictly match the DLL.
- Support complex types (structures, pointers) and need to be used
Structure
kind.
3. Advanced features
Callback function:
public interface CallbackLib extends Library { interface Callback extends CallbackProxy { void invoke(String result); } void registerCallback(Callback callback); }
Structure map:
public class Point extends Structure { public int x; public int y; }
4. Frequently Asked Questions
-
UnsatisfiedLinkError:
- Check the DLL name and path to make sure that the 32/64 bits are consistent.
-
Parameter type mismatch:
- use
()
Debug type size.
- use
Summarize
- C# calls Java: Prioritize the use of IKVM simple scenarios, JNI is used for high-performance requirements.
- Java calls DLL:JNA is the simplest solution, without writing C code.
- Code maintainability: Cross-language calls require detailed documentation of interface conventions.
The above is the detailed content of the method of calling C# and Java to each other. For more information about calling C# and Java to each other, please pay attention to my other related articles!