Table of Contents

Java simple example

C# class use example

This is a basic example where a Java application calls the simple class defined in a file named CSharpClass.cs.

Consider the following C# code:

using System;

namespace MASES.CLRTests
{
    public class CSharpClass
    {
        /// <summary>The method <c>HelloWorld</c> returns the "Hello World!!" string</summary>
        public String HelloWorld()
        {
            return "Hello World from C#!!";
        }

        /// <summary>The method <c>Add</c> returns the sum of two doubles</summary>
        public double Add(double a, double b)
        {
            return a + b;
        }

        /// <summary>The method <c>Sin</c> returns the sine of a double</summary>
        public double Sin(double a)
        {
            return Math.Sin(a);
        }
    }
}

Compile it with your preferred development tools to generate an assembly.

Create a Java class named CSharpClassUseExample.java with the following content:

import java.io.IOException;
import org.mases.jcobridge.*;

public class CSharpClassUseExample {
    public static void main(String[] args) {
        try {
            try {
                try {
                    JCOBridge.Initialize();
                } catch (JCException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // declare and create JCOBridge instance
            JCOBridge bridge;
            bridge = JCOBridge.CreateNew();
            // adds the path where external assemblies are found
            bridge.AddPath("./");
            // add a reference to the .dll file
            bridge.AddReference("CSharpClass");
            // generate the object
            JCObject cso = (JCObject) bridge.NewObject("MASES.CLRTests.CSharpClass");
            double a = 2;
            double b = 3;
            double c = Math.PI/2;
            // invoke the C# class methods
            String hello = (String) cso.Invoke("HelloWorld");
            double result = (double) cso.Invoke("Add", a, b);
            double sin = (double) cso.Invoke("Sin", c);
            System.out.println(String.format("%s %.0f + %.0f = %.0f and sin(%.8f) = %.8f", hello, a, b, result, c, sin));
        } catch (JCException jce) {
            jce.printStackTrace();
            System.out.println("Exiting");
            return;
        }
    }
}

Save the file in the folder that holds the assembly generated from the C# project and run the Java class as a standard main class.

The output is:

Hello World from C#!! 2 + 3 = 5 and sin(3,14159265) = 1,00000000