Beispiel #1
0
        protected virtual void Dispose(bool disposing)
        {
            // free native resources if there are any.
            if (javaClass != IntPtr.Zero)
            {
                env.DeleteGlobalRef(javaClass);
                javaClass = IntPtr.Zero;
            }

            if (javaObject != IntPtr.Zero)
            {
                env.DeleteLocalRef(javaObject);
                javaObject = IntPtr.Zero;
            }

            if (disposing)
            {
                // free managed resources
                if (jvm != null)
                {
                    jvm.Dispose();
                    jvm = null;
                }

                if (env != null)
                {
                    env.Dispose();
                    env = null;
                }
            }
        }
Beispiel #2
0
        private void AttachToCurrentJVM(JavaVMInitArgs args)
        {
            // This is only required if you want to reuse the same instance of the JVM
            // This is especially useful if you are using JNI in a webservice. see page 89 of the
            // Java Native Interface: Programmer's Guide and Specification by Sheng Liang
            if (AttachToCurrentJVMThread)
            {
                int nVMs;

                IntPtr javaVirtualMachine;
                int    res = JavaVM.JNI_GetCreatedJavaVMs(out javaVirtualMachine, 1, out nVMs);
                if (res != JNIReturnValue.JNI_OK)
                {
                    throw new Exception("JNI_GetCreatedJavaVMs failed (" + res.ToString() + ")");
                }
                if (nVMs > 0)
                {
                    jvm = new JavaVM(javaVirtualMachine);
                    res = jvm.AttachCurrentThread(out env, args);
                    if (res != JNIReturnValue.JNI_OK)
                    {
                        throw new Exception("AttachCurrentThread failed (" + res.ToString() + ")");
                    }
                }
            }
        }
Beispiel #3
0
        public void LoadVM(Dictionary <string, string> options)
        {
            string currentDir = Directory.GetCurrentDirectory();
            string jvmDll     = Path.Combine("jre", "bin", "server", "jvm.dll");

            if ((!File.Exists(jvmDll)))
            {
                throw new Exception("Error determining the location of the Java Runtime Environment");
            }

            // Set the directory to the location of the JVM.dll.
            // This will ensure that the API call JNI_CreateJavaVM will work
            Directory.SetCurrentDirectory(Path.GetDirectoryName(jvmDll));

            var args = new JavaVMInitArgs();

            args.version            = JNIVersion.JNI_VERSION_10;
            args.ignoreUnrecognized = JavaVM.BooleanToByte(true); // True

            if (options.Count > 0)
            {
                args.nOptions = options.Count;
                var opt = new JavaVMOption[options.Count];
                int i   = 0;
                foreach (KeyValuePair <string, string> kvp in options)
                {
                    opt[i++].optionString = Marshal.StringToHGlobalAnsi(kvp.Key.ToString() + "=" + kvp.Value.ToString());
                }

                fixed(JavaVMOption *a = &opt[0])
                {
                    // prevents the garbage collector from relocating the opt variable as this is used in unmanaged code that the gc does not know about
                    args.options = a;
                }
            }

            var result = JavaVM.JNI_CreateJavaVM(out IntPtr javaVirtualMachine, out IntPtr environment, &args);

            if (result != JNIReturnValue.JNI_OK)
            {
                throw new Exception("Cannot create JVM " + result.ToString());
            }

            jvm = new JavaVM(javaVirtualMachine);
            env = new JNIEnv(environment);

            Directory.SetCurrentDirectory(currentDir);
        }
Beispiel #4
0
        public void LoadVM(Dictionary <string, string> options, bool AddToExistingJVM)
        {
            // Get the location of the current version of the JVM.dll
            string jreVersion = (string)Registry.GetValue(JRE_REGISTRY_KEY, "CurrentVersion", null);
            string keyName    = Path.Combine(JRE_REGISTRY_KEY, jreVersion);

            string jvmDir = (string)Registry.GetValue(keyName, "RuntimeLib", null);

            if ((jvmDir.Length == 0) || (!File.Exists(jvmDir)))
            {
                throw new Exception("Error determining the location of the Java Runtime Environment");
            }

            // Set the directory to the location of the JVM.dll.
            // This will ensure that the API call JNI_CreateJavaVM will work
            Directory.SetCurrentDirectory(Path.GetDirectoryName(jvmDir));

            var args = new JavaVMInitArgs();

            switch (Convert.ToInt32((decimal.Parse(jreVersion.Substring(0, 3)) - 1) / 2 * 10))
            {
            case 0:
                throw new Exception("Unsupported java version. Please upgrade your version of the JRE.");

            case 1:
                args.version = JNIVersion.JNI_VERSION_1_2;
                break;

            case 2:
                args.version = JNIVersion.JNI_VERSION_1_4;
                break;

            default:
                args.version = JNIVersion.JNI_VERSION_1_6;
                break;
            }

            args.ignoreUnrecognized = JavaVM.BooleanToByte(true); // True

            if (options.Count > 0)
            {
                args.nOptions = options.Count;
                var opt = new JavaVMOption[options.Count];
                int i   = 0;
                foreach (KeyValuePair <string, string> kvp in options)
                {
                    opt[i++].optionString = Marshal.StringToHGlobalAnsi(kvp.Key.ToString() + "=" + kvp.Value.ToString());
                }

                fixed(JavaVMOption *a = &opt[0])
                {
                    // prevents the garbage collector from relocating the opt variable as this is used in unmanaged code that the gc does not know about
                    args.options = a;
                }
            }

            if (!AttachToCurrentJVMThread)
            {
                IntPtr environment;
                IntPtr javaVirtualMachine;
                int    result = JavaVM.JNI_CreateJavaVM(out javaVirtualMachine, out environment, &args);
                if (result != JNIReturnValue.JNI_OK)
                {
                    throw new Exception("Cannot create JVM " + result.ToString());
                }

                jvm = new JavaVM(javaVirtualMachine);
                env = new JNIEnv(environment);
            }
            else
            {
                AttachToCurrentJVM(args);
            }
        }
Beispiel #5
0
        private JValue[] ParseParameters(string sig, List <object> param)
        {
            JValue[] retval = new JValue[param.Count];

            int startIndex = sig.IndexOf('(') + 1;

            for (int i = 0; i < param.Count; i++)
            {
                string paramSig = "";
                if (sig.Substring(startIndex, 1) == "[")
                {
                    paramSig = sig.Substring(startIndex++, 1);
                }

                if (sig.Substring(startIndex, 1) == "L")
                {
                    paramSig = paramSig + sig.Substring(startIndex, sig.IndexOf(';', startIndex) - startIndex);
                    startIndex++; // skip past ;
                }
                else
                {
                    paramSig = paramSig + sig.Substring(startIndex, 1);
                }

                startIndex = startIndex + (paramSig.Length - (paramSig.IndexOf("[", StringComparison.Ordinal) + 1));

                if (param[i] is string)
                {
                    if (!paramSig.Equals("Ljava/lang/String"))
                    {
                        throw new Exception("Signature (" + paramSig + ") does not match parameter value (" + param[i].GetType().ToString() + ").");
                    }
                    retval[i] = new JValue()
                    {
                        l = env.NewString(param[i].ToString(), param[i].ToString().Length)
                    };
                }
                else if (param[i] == null)
                {
                    retval[i] = new JValue(); // Just leave as default value
                }
                else if (paramSig.StartsWith("["))
                {
                    retval[i] = ProcessArrayType(paramSig, param[i]);
                }
                else
                {
                    retval[i] = new JValue();
                    FieldInfo paramField = retval[i].GetType().GetFields(BindingFlags.Public | BindingFlags.Instance).AsQueryable().FirstOrDefault(a => a.Name.ToUpper().Equals(paramSig));
                    if ((paramField != null) && ((param[i].GetType() == paramField.FieldType) || ((paramField.FieldType == typeof(bool)) && (param[i] is byte))))
                    {
                        paramField.SetValueDirect(__makeref(retval[i]), paramField.FieldType == typeof(bool)  // this is an undocumented feature to set struct fields via reflection
                                                      ? JavaVM.BooleanToByte((bool)param[i])
                                                      : param[i]);
                    }
                    else
                    {
                        throw new Exception("Signature (" + paramSig + ") does not match parameter value (" + param[i].GetType().ToString() + ").");
                    }
                }
            }
            return(retval);
        }