SoFunction
Updated on 2025-03-07

C# to call Java class implementation method

1. Package the compiled Java Class file; package command JAR
For example: package all class folders in a certain directory;
Commands used: jar cvf -C com/.
It is the jar package to be generated; com/. is the folder in the specified current directory, which includes subfolders and class files;

2. Go to the official IKVM website to download the components required by IKVM /
ikvm-0.42.0.
ikvmbin-0.42.0.

3. Set the path
Decompress ikvm-0.42.0. and add %IKVM_HOME%\bin to path. The %IKVM_HOME% here refers to the home directory of the ikvm after decompression.

4. Convert java jar package to .dll control
Command used: ikvmc -out:
It is the name of the .dll control file to be generated; it is the jar package file that was packaged before.

5. Add required controls to C# project

1. Create a new C# .NET project and first add the necessary DLLs
%IKVM_HOME%\bin\
%IKVM_HOME%\bin\
%IKVM_HOME%\bin\

2. Add the generated .dll file
Load the previously generated .dll file into a C# project

VI. Test
Use java classes in C# projects, and their methods are the same as java. But using the C# syntax using the reference to package

source code:
Java source code:

Copy the codeThe code is as follows:

package ;
//The Java class to be called
public class Test {
//The Java method to be called
    public String returnString() {
        return "Hello, zht!";
    }

}


C# form source code:
Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace KIVMTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Test t = new Test();
            string str = ();
            (str);
        }
    }
}


result:
After starting the C# window, the prompt window is displayed, with the content: Hello, zht!