SoFunction
Updated on 2025-04-14

Summary of the method of calling C# and Java between each other

C# calls Java classes and methods (IKVM / JNI-JNA bridge)

1. Prerequisites

  1. Environmental Requirements
    • IKVM: Install the IKVM toolkit (includingikvmcikvmand other tools), requiring JDK and .NET Framework.
    • JNI/JNA: Requires Java JDK (includingjavacjavah) and .NET P/Invoke support.
  2. Document preparation
    • Java JAR package (such as)。
    • The complete definition of Java classes (need to expose the target class and methods).

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 arepublicof.
  • 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

  1. IKVM conversion failed
    • When the dependency JAR package is missing, you need to add-reference:
  2. JNI memory leak
    • useReleaseStringUTFCharsFree resources.
  3. DLL path issues
    • Make sure the DLL is in the output directory orPATHIn environment variables.

V. Advanced Features

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

  1. Environmental Requirements
    • Java 8+, installationJNA Library
  2. Document preparation
    • Target DLL (such as) and its function signatures.

2. Use the JNA method

principle: Directly map DLL functions to Java interfaces through the JNA library, without writing C code.

Implementation steps:

  1. 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 usedStructurekind.

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

  1. UnsatisfiedLinkError
    • Check the DLL name and path to make sure that the 32/64 bits are consistent.
  2. Parameter type mismatch
    • use()Debug type size.

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!