using System.Runtime.InteropServices; class Program { [DllImport("myLibrary.dll")] public static extern int myFunction(int arg1, int arg2); static void Main(string[] args) { int result = myFunction(3, 4); Console.WriteLine(result); } }
using System; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { IntPtr javaVM; // pointer to Java Virtual Machine // create Java Virtual Machine IntPtr envPointer; JNIEnv.GetDefaultJavaVMInitArgs(out JavaVMInitArgs vmArgs); JNI.CreateJavaVM(out javaVM, out envPointer, ref vmArgs); // get a class object and its constructor method IntPtr javaClass = JNI.FindClass(envPointer, "my/package/MyClass"); IntPtr constructor = JNI.GetMethodID(envPointer, javaClass, "In this example, we use JNI functions to create a Java Virtual Machine and call a method on a Java object. We first get the class object and constructor method of our target class. We then create a new object of that class and call a method on it, passing a string argument. Finally, we delete the object and destroy the Java Virtual Machine. The package for the JNI library is usually platform-specific and provided by the vendor of the JDK or JRE. For example, on Windows, the JNI library is typically found in the "bin" directory of the JDK installation and named "jvm.dll". On Linux, it is often found in the "lib" directory and named "libjvm.so".", "()V"); // create a new Java object IntPtr javaObject = JNI.NewObject(envPointer, javaClass, constructor); // call a Java method on the object IntPtr method = JNI.GetMethodID(envPointer, javaClass, "myMethod", "(Ljava/lang/String;)V"); IntPtr argument = JNI.NewStringUTF(envPointer, "Hello from C#"); JNI.CallVoidMethod(envPointer, javaObject, method, argument); // delete the Java object JNI.DeleteLocalRef(envPointer, javaObject); // destroy the Java Virtual Machine JNI.DestroyJavaVM(javaVM); } }