IKVM C# to Java Interop with Callback using IKVM

前端 未结 2 1512
梦毁少年i
梦毁少年i 2021-02-06 18:10

I\'ve started using IKVM to translate Java libs into .NET CIL. I can successfully write a C# program that pulls in (inproc) a translated Java assembly as a reference and make ca

2条回答
  •  再見小時候
    2021-02-06 18:29

    Ladies and Gentlemen, I figured out my own question. Code first followed by steps.

    Java Class

    public class TestClass {
    private cli.CSharpLibrary.Library m_lib = null;
    
    public void AddDelegate( cli.CSharpLibrary.Library lib )
    {
        m_lib = lib;
    }
    
    public void FireDelegate()
    {
        if( m_lib != null )
        {
            m_lib.ExecuteRunnableDelegate();
        }
    }
    
    public void PrintInt()
    {
        System.out.print(23);
    }
    }
    

    C# Class

    using ikvm.runtime;
    using CSharpLibrary;
    
    namespace CSharp
    {
      class Program
      {
    public static void DelegateTarget()
    {
      Console.WriteLine("DelegateTarget Executed!");
    }
    
    static void Main(string[] args)
    {
      Library lib = new Library();
      lib.m_runnableDelegate = new Delegates.RunnableDelegate(DelegateTarget);
    
      TestClass tc = new TestClass();
      tc.AddDelegate(lib);
      tc.FireDelegate();
    
    }
    }
    }
    

    1) Write your Java app

    2) Convert your *.class files into a jar file (jar -cf myjar.jar *.class)

    3) Convert the jar file into a .NET assembly (ikvmc -reference:csharpassembly.dll myjar.jar)

    Should work at this point. You can run your C# program, have it call the converted Java program and vice versa. Watch out for the "-reference" flag on the ikvmc call. This tells IKVM when it's converting the Java code that csharpassembly.dll has some class definitions that it needs to watch out for.

提交回复
热议问题