C calls the implementation of the Java class

  • 2020-05-19 05:31:43
  • OfStack

1. Package the Class files in the compiled java; Package the command JAR
For example, package all the class folders under a certain directory;
Command to use: jar cvf test. jar-C com/.
Where test.jar is the jar package to be generated; com/. Is the folder in the specified current directory, which includes subfolders and class files;

2. Need to IKVM official website to download IKVM component http: / / www ikvm. net /
ikvm - 0.42.0.3. zip
ikvmbin - 0.42.0.3. zip
openjdk6 b16 - stripped zip

3. Set the path
Unzip ikvm-0.42.0.3.zip and add %IKVM_HOME%\bin to path. Here %IKVM_HOME% is the home directory of ikvm after unzipping.

4. Convert java's jar package to a.dll control
Command to use: ikvmc-out: IKVM.dll test.jar
Where IKVM.dll is the file name of the.dll control to be generated; test.jar is the jar package file that was previously packaged.

5. Add the required controls in the C# project

1. Create a new C#.NET project, and first add 1 required DLLs
% IKVM_HOME % \ bin \ IKVM OpenJDK. Core. dll
% IKVM_HOME % \ bin \ IKVM Runtime. dll
% IKVM_HOME % \ bin \ IKVM Runtime. JNI. dll

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

Test 6.
The java class is used in the C# project in the same way as java. But the reference to the package USES the syntax C#, using

The source code:
Java source code:


package com.zht;
// To call Java class  
public class Test {
   // To call Java methods  
    public String returnString() {
        return "Hello, zht!";
    }
}

C# form source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using com.zht; 
namespace KIVMTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Test t = new Test(); 
            string str = t.returnString(); 
            MessageBox.Show(str);
        }
    }
}

Results:
After launching C# window, the prompt window will be displayed. The content is: Hello, zht!


Related articles: