CSharp Class Use Examples
This is a basic example where a developer call, from a Java application, the simple class defined in a file named CSharpClass.cs.
Let’s consider the following C# code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using System; namespace MASES.CLRTests { public class CSharpClass { /// <summary>The method <c>HelloWorld</c> return the "Hello World!!" string</summary> public String HelloWorld() { return "Hello World from C#!!" ; } /// <summary>The method <c>Add</c> return the sum of two double</summary> public double Add( double a, double b) { return a + b; } /// <summary>The method <c>Add</c> return the sin of a double</summary> public double Sin( double a) { return Math.Sin(a); } } } |
Compiling it with the preferred development tools an assembly will be generated.
Create a Java class named CSharpClassUseExample.java with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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 extarnal assemblies where found bridge.AddPath( "./" ); // add REFERENCES to the .dll file bridge.AddReference( "CSharpClass" ); // GENERATE 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 same folder where is located the assembly generated from C# project and execute the Java class as standard Main-Class.
Executing the code the following output will be generated:
Hello World from C#!! 2 + 3 = 5 and sin(3,14159265) = 1,00000000 |