Ejemplo n.º 1
0
 public unsafe void GetValue_FindBestMatchType()
 {
     using (var t = new JniType(TestType.JniTypeName)) {
         var c = t.GetConstructor("()V");
         var o = t.NewObject(c, null);
         using (var w = JniRuntime.CurrentRuntime.ValueManager.GetValue <IJavaPeerable> (ref o, JniObjectReferenceOptions.CopyAndDispose)) {
             Assert.AreEqual(typeof(TestType), w.GetType());
             Assert.IsTrue(((TestType)w).ExecutedActivationConstructor);
         }
     }
 }
Ejemplo n.º 2
0
        static unsafe JniObjectReference CreateThrowable(JniType type, string message)
        {
            var c = type.GetConstructor("(Ljava/lang/String;)V");
            var s = JniEnvironment.Strings.NewString(message);

            try {
                var args = stackalloc JniArgumentValue [1];
                args [0] = new JniArgumentValue(s);
                return(type.NewObject(c, args));
            } finally {
                JniObjectReference.Dispose(ref s);
            }
        }
Ejemplo n.º 3
0
 public unsafe void IsInstanceOfType()
 {
     using (var Object_class = new JniType("java/lang/Object"))
         using (var String_class = new JniType("java/lang/String")) {
             var String_ctor = String_class.GetConstructor("()V");
             var s           = String_class.NewObject(String_ctor, null);
             try {
                 Assert.IsTrue(Object_class.IsInstanceOfType(s), "java.lang.String IS-NOT-A java.lang.Object?!");
             } finally {
                 JniObjectReference.Dispose(ref s);
             }
         }
 }
Ejemplo n.º 4
0
 public unsafe void Types_IsSameObject()
 {
     using (var t = new JniType("java/lang/Object")) {
         var c = t.GetConstructor("()V");
         var o = t.NewObject(c, null);
         try {
             using (var ot = JniEnvironment.Types.GetTypeFromInstance(o)) {
                 Assert.IsTrue(JniEnvironment.Types.IsSameObject(t.PeerReference, ot.PeerReference));
             }
         } finally {
             JniObjectReference.Dispose(ref o);
         }
     }
 }
Ejemplo n.º 5
0
        public static unsafe void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            try {
                var ignore = JniRuntime.CurrentRuntime;
            } catch (InvalidOperationException e) {
                Console.WriteLine(e);
            }
            foreach (var h in JniRuntime.GetAvailableInvocationPointers())
            {
                Console.WriteLine("PRE: GetCreatedJavaVMHandles: {0}", h);
            }
            Console.WriteLine("Part 2!");
            using (var vm = new JreRuntimeOptions().CreateJreVM()) {
                Console.WriteLine("# JniEnvironment.EnvironmentPointer={0}", JniEnvironment.EnvironmentPointer);
                Console.WriteLine("vm.SafeHandle={0}", vm.InvocationPointer);
                var t = new JniType("java/lang/Object");
                var c = t.GetConstructor("()V");
                var o = t.NewObject(c, null);
                var m = t.GetInstanceMethod("hashCode", "()I");
                int i = JniEnvironment.InstanceMethods.CallIntMethod(o, m);
                Console.WriteLine("java.lang.Object={0}", o);
                Console.WriteLine("hashcode={0}", i);
                JniObjectReference.Dispose(ref o);
                t.Dispose();
                // var o = JniTypes.FindClass ("java/lang/Object");

                /*
                 * var waitForCreation = new CountdownEvent (1);
                 * var exitThread = new CountdownEvent (1);
                 * var t = new Thread (() => {
                 *      var vm2 = new JavaVMBuilder ().CreateJavaVM ();
                 *      waitForCreation.Signal ();
                 *      exitThread.Wait ();
                 * });
                 * t.Start ();
                 * waitForCreation.Wait ();
                 */
                foreach (var h in JniRuntime.GetAvailableInvocationPointers())
                {
                    Console.WriteLine("WITHIN: GetCreatedJavaVMs: {0}", h);
                }
                // exitThread.Signal ();
            }
            foreach (var h in JniRuntime.GetAvailableInvocationPointers())
            {
                Console.WriteLine("POST: GetCreatedJavaVMs: {0}", h);
            }
        }
Ejemplo n.º 6
0
 public unsafe void Ctor()
 {
     using (var t = new JniType("java/lang/Object")) {
         var c    = t.GetConstructor("()V");
         var lref = t.NewObject(c, null);
         Assert.IsTrue(lref.IsValid);
         using (var o = new JavaObject(ref lref, JniObjectReferenceOptions.Copy)) {
             Assert.IsTrue(lref.IsValid);
             Assert.AreNotSame(lref, o.PeerReference);
         }
         using (var o = new JavaObject(ref lref, JniObjectReferenceOptions.CopyAndDispose)) {
             Assert.IsFalse(lref.IsValid);
             Assert.AreNotSame(lref, o.PeerReference);
         }
     }
 }
Ejemplo n.º 7
0
 public unsafe void Handles_NewReturnToJniRef()
 {
     using (var t = new JniType("java/lang/Object")) {
         var c = t.GetConstructor("()V");
         var o = t.NewObject(c, null);
         try {
             var n = o.NewLocalRef();
             JniObjectReference.Dispose(ref n);
             // warning: lref 'leak'
             var r = JniEnvironment.References.NewReturnToJniRef(o);
             var h = new JniObjectReference(r);
             Assert.AreEqual(JniEnvironment.References.GetIdentityHashCode(o), JniEnvironment.References.GetIdentityHashCode(h));
         } finally {
             JniObjectReference.Dispose(ref o);
         }
     }
 }
Ejemplo n.º 8
0
        public unsafe void Sanity()
        {
            using (var Integer_class = new JniType("java/lang/Integer")) {
                Assert.AreEqual("java/lang/Integer", Integer_class.Name);

                var ctor_args = stackalloc JniArgumentValue [1];
                ctor_args [0] = new JniArgumentValue(42);

                var Integer_ctor     = Integer_class.GetConstructor("(I)V");
                var Integer_intValue = Integer_class.GetInstanceMethod("intValue", "()I");
                var o = Integer_class.NewObject(Integer_ctor, ctor_args);
                try {
                    int v = JniEnvironment.InstanceMethods.CallIntMethod(o, Integer_intValue);
                    Assert.AreEqual(42, v);
                } finally {
                    JniObjectReference.Dispose(ref o);
                }
            }
        }
Ejemplo n.º 9
0
        unsafe TimeSpan GetJIMethodCallTiming()
        {
            using (var k = new JniType("java/lang/Object")) {
                var c = k.GetConstructor("()V");
                var o = k.NewObject(c, null);
                var t = k.GetInstanceMethod("toString", "()Ljava/lang/String;");

                var sw = Stopwatch.StartNew();
                for (int i = 0; i < Unified_ToString_Iterations; ++i)
                {
                    var r = JniEnvironment.InstanceMethods.CallObjectMethod(o, t);
                    JniObjectReference.Dispose(ref r);
                }
                sw.Stop();

                JniObjectReference.Dispose(ref o);
                return(sw.Elapsed);
            }
        }
Ejemplo n.º 10
0
        public unsafe void MethodInvocationTiming()
        {
            FooMethods pinvoke_methods;

            foo_get_methods(out pinvoke_methods);

            var p_instance_void = (DV)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_void, typeof(DV));
            var p_instance_int  = (DI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_int, typeof(DI));
            var p_instance_ptr  = (DP)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_ptr, typeof(DP));

            var p_void_1a = (DV1A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_args, typeof(DV1A));
            var p_void_2a = (DV2A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_args, typeof(DV2A));
            var p_void_3a = (DV3A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_args, typeof(DV3A));

            var p_void_1ai = (DV1AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_iargs, typeof(DV1AI));
            var p_void_2ai = (DV2AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_iargs, typeof(DV2AI));
            var p_void_3ai = (DV3AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_iargs, typeof(DV3AI));

            var Object_class = new JniType("java/lang/Object");
            var Object_init  = Object_class.GetConstructor("()V");

            var transfer = JniObjectReferenceOptions.CopyAndDispose;

            var jobj1 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);
            var jobj2 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);
            var jobj3 = CreateJavaObject(Object_class.NewObject(Object_init, null), transfer);

            var obj1 = new SomeClass();
            var obj2 = new SomeClass();
            var obj3 = new SomeClass();

            var j           = new JavaTiming();
            var m           = new ManagedTiming();
            var comparisons = new[] {
                new {
                    Name    = "static void",
                    Jni     = A(() => JavaTiming.StaticVoidMethod()),
                    Managed = A(() => ManagedTiming.StaticVoidMethod()),
                    Pinvoke = A(() => foo_void_timing()),
                },
                new {
                    Name    = "static int",
                    Jni     = A(() => JavaTiming.StaticIntMethod()),
                    Managed = A(() => ManagedTiming.StaticIntMethod()),
                    Pinvoke = A(() => foo_int_timing()),
                },
                new {
                    Name    = "static object",
                    Jni     = A(() => JavaTiming.StaticObjectMethod()),
                    Managed = A(() => ManagedTiming.StaticObjectMethod()),
                    Pinvoke = A(() => foo_ptr_timing()),
                },
                new {
                    Name    = "virtual void",
                    Jni     = A(() => j.VirtualVoidMethod()),
                    Managed = A(() => m.VirtualVoidMethod()),
                    Pinvoke = A(() => p_instance_void()),
                },
                new {
                    Name    = "virtual int",
                    Jni     = A(() => j.VirtualIntMethod()),
                    Managed = A(() => m.VirtualIntMethod()),
                    Pinvoke = A(() => p_instance_int()),
                },
                new {
                    Name    = "virtual object",
                    Jni     = A(() => j.VirtualObjectMethod()),
                    Managed = A(() => m.VirtualObjectMethod()),
                    Pinvoke = A(() => p_instance_ptr()),
                },
                new {
                    Name    = "final void",
                    Jni     = A(() => j.FinalVoidMethod()),
                    Managed = A(() => m.FinalVoidMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "final int",
                    Jni     = A(() => j.FinalIntMethod()),
                    Managed = A(() => m.FinalIntMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "final object",
                    Jni     = A(() => j.FinalObjectMethod()),
                    Managed = A(() => m.FinalObjectMethod()),
                    Pinvoke = A(null),
                },
                new {
                    Name    = "static void o1",
                    Jni     = A(() => JavaTiming.StaticVoidMethod1Args(jobj1)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod1Args(obj1)),
                    Pinvoke = A(() => {
                        // We include timing of the GCHandle manipulation since
                        // a JNI invocation has to do similar work, and pinning
                        // is usually always needed for P/Invokes.
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject();

                        p_void_1a(addr1);

                        h1.Free();
                    }),
                },
                new {
                    Name    = "static void o2",
                    Jni     = A(() => JavaTiming.StaticVoidMethod2Args(jobj1, jobj2)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod2Args(obj1, obj2)),
                    Pinvoke = A(() => {
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned),
                        h2           = GCHandle.Alloc(obj2, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject(),
                        addr2        = h2.AddrOfPinnedObject();

                        p_void_2a(addr1, addr2);

                        h1.Free();
                        h2.Free();
                    }),
                },
                new {
                    Name    = "static void o3",
                    Jni     = A(() => JavaTiming.StaticVoidMethod3Args(jobj1, jobj2, jobj3)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod3Args(obj1, obj2, obj3)),
                    Pinvoke = A(() => {
                        GCHandle h1  = GCHandle.Alloc(obj1, GCHandleType.Pinned),
                        h2           = GCHandle.Alloc(obj2, GCHandleType.Pinned),
                        h3           = GCHandle.Alloc(obj3, GCHandleType.Pinned);
                        IntPtr addr1 = h1.AddrOfPinnedObject(),
                        addr2        = h2.AddrOfPinnedObject(),
                        addr3        = h3.AddrOfPinnedObject();

                        p_void_3a(addr1, addr2, addr3);

                        h1.Free();
                        h2.Free();
                        h3.Free();
                    }),
                },
                new {
                    Name    = "static void i1",
                    Jni     = A(() => JavaTiming.StaticVoidMethod1IArgs(42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod1IArgs(42)),
                    Pinvoke = A(() => p_void_1ai(42)),
                },
                new {
                    Name    = "static void i2",
                    Jni     = A(() => JavaTiming.StaticVoidMethod2IArgs(42, 42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod2IArgs(42, 42)),
                    Pinvoke = A(() => p_void_2ai(42, 42)),
                },
                new {
                    Name    = "static void i3",
                    Jni     = A(() => JavaTiming.StaticVoidMethod3IArgs(42, 42, 42)),
                    Managed = A(() => ManagedTiming.StaticVoidMethod3IArgs(42, 42, 42)),
                    Pinvoke = A(() => p_void_3ai(42, 42, 42)),
                },
            };

#if __ANDROID__
            const int count = 1000;
#else   // __ANDROID__
            const int count = 100000;
#endif  // __ANDROID__

            var total = Stopwatch.StartNew();

            foo_init(JniEnvironment.EnvironmentPointer);

            var jniTimes = new long [comparisons.Length];
            foo_get_native_jni_timings(JniEnvironment.EnvironmentPointer, count, JavaTiming.TypeRef.PeerReference.Handle, j.PeerReference.Handle, jniTimes);

            int jniTimeIndex = 0;
            foreach (var c in comparisons)
            {
                var jw = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < count; ++i)
                {
                    c.Jni();
                }
                jw.Stop();

                var mw = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < count; ++i)
                {
                    c.Managed();
                }
                mw.Stop();

                System.Diagnostics.Stopwatch pw = null;
                if (c.Pinvoke != null)
                {
                    pw = System.Diagnostics.Stopwatch.StartNew();
                    for (int i = 0; i < count; ++i)
                    {
                        c.Pinvoke();
                    }
                    pw.Stop();
                }

                string message = string.Format("Method Invoke: {0}: JNI is {1}x managed",
                                               c.Name, System.Math.Round(jw.Elapsed.TotalMilliseconds / mw.Elapsed.TotalMilliseconds));
                Console.WriteLine(message);

                var ct = TimeSpan.FromMilliseconds(jniTimes [jniTimeIndex++]);
                Console.WriteLine("\t  C/JNI: {0} ms               | average: {1} ms",
                                  FormatFraction(ct.TotalMilliseconds, 10, 5),
                                  FormatFraction(ct.TotalMilliseconds / count, 12, 5));
                Console.WriteLine("\t    JNI: {0} ms; {1,3}x C/JNI   | average: {2} ms",
                                  FormatFraction(jw.Elapsed.TotalMilliseconds, 10, 5),
                                  ToString(jw.Elapsed, ct),
                                  FormatFraction(jw.Elapsed.TotalMilliseconds / count, 12, 5));
                Console.WriteLine("\tManaged: {0} ms               | average: {1} ms",
                                  FormatFraction(mw.Elapsed.TotalMilliseconds, 10, 5),
                                  FormatFraction(mw.Elapsed.TotalMilliseconds / count, 12, 5));
                if (pw != null)
                {
                    Console.WriteLine("\tPinvoke: {0} ms; {1,3}x managed | average: {2} ms",
                                      FormatFraction(pw.Elapsed.TotalMilliseconds, 10, 5),
                                      ToString(pw.Elapsed, mw.Elapsed),
                                      FormatFraction(pw.Elapsed.TotalMilliseconds / count, 12, 5));
                }
            }

            total.Stop();
            Console.WriteLine("## {0} Timing: {1}", nameof(MethodInvocationTiming), total.Elapsed);
        }
Ejemplo n.º 11
0
        public unsafe void ObjectCreationTiming()
        {
            const int C = 100;

            var total = Stopwatch.StartNew();

            Stopwatch allocTime, newObjectTime, newTime, getObjectTime;

            using (var Object_class = new JniType("java/lang/Object")) {
                var Object_init = Object_class.GetConstructor("()V");
                allocTime = Stopwatch.StartNew();
                for (int i = 0; i < C; ++i)
                {
                    var h = Object_class.AllocObject();
                    JniObjectReference.Dispose(ref h);
                }
                allocTime.Stop();

                newObjectTime = Stopwatch.StartNew();
                for (int i = 0; i < C; ++i)
                {
                    var h = Object_class.NewObject(Object_init, null);
                    JniObjectReference.Dispose(ref h);
                }
                newObjectTime.Stop();

                newTime = Stopwatch.StartNew();
                var olist = new List <JavaObject> (C);
                for (int i = 0; i < C; ++i)
                {
                    olist.Add(new JavaObject());
                }
                newTime.Stop();
                foreach (var o in olist)
                {
                    o.Dispose();
                }

                var strings = new JavaObjectArray <string> (100);
                for (int i = 0; i < 100; ++i)
                {
                    strings [i] = i.ToString();
                }

                using (strings) {
                    var vm    = JniEnvironment.Runtime;
                    var rlist = new List <JavaObject> (C);
                    getObjectTime = Stopwatch.StartNew();
                    for (int i = 0; i < C; ++i)
                    {
                        var h = JniEnvironment.Arrays.GetObjectArrayElement(strings.PeerReference, i);
                        var o = vm.ValueManager.GetValue <JavaObject> (ref h, JniObjectReferenceOptions.CopyAndDispose);
                        rlist.Add(o);
                    }
                    getObjectTime.Stop();
                    foreach (var o in rlist)
                    {
                        o.DisposeUnlessReferenced();
                    }
                }
            }

            total.Stop();
            Console.WriteLine("## {0} Timing: Total={1} AllocObject={2} NewObject={3} `new JavaObject()`={4} JavaVM.GetObject()={5}",
                              nameof(ObjectCreationTiming), total.Elapsed, allocTime.Elapsed, newObjectTime.Elapsed, newTime.Elapsed, getObjectTime.Elapsed);
        }
Ejemplo n.º 12
0
        unsafe void GetJICallObjectMethodAndDeleteLocalRefTimings(
            out TimeSpan callVirtualObjectMethodTime, out TimeSpan disposeTime,
            out TimeSpan safeCallObjectMethodTime, out TimeSpan safeDeleteLocalRefTime,
            out TimeSpan unsafeCallObjectMethodTime, out TimeSpan unsafeDeleteLocalRefTime)
        {
            using (var k = new JniType("java/lang/Object")) {
                var c = k.GetConstructor("()V");
                var o = k.NewObject(c, null);
                var t = k.GetInstanceMethod("toString", "()Ljava/lang/String;");

                var r = JniEnvironment.InstanceMethods.CallObjectMethod(o, t);
                JniObjectReference.Dispose(ref r);

                var rs = new JniObjectReference [MaxLocalRefs];

                var sw = Stopwatch.StartNew();
                for (int i = 0; i < rs.Length; ++i)
                {
                    rs [i] = JniEnvironment.InstanceMethods.CallObjectMethod(o, t);
                }
                sw.Stop();
                callVirtualObjectMethodTime = sw.Elapsed;

                sw.Restart();
                for (int i = 0; i < rs.Length; ++i)
                {
                    JniObjectReference.Dispose(ref rs [i]);
                }
                sw.Stop();
                disposeTime = sw.Elapsed;

                IntPtr JNIEnv_CallObjectMethodA = Marshal.ReadIntPtr(Marshal.ReadIntPtr(JNIEnv.Handle), JNIEnvOffset_CallObjectMethodA);
                IntPtr JNIEnv_DeleteLocalRef    = Marshal.ReadIntPtr(Marshal.ReadIntPtr(JNIEnv.Handle), JNIEnvOffset_DeleteLocalRef);

                var safeCall = (SafeHandleDelegate_CallObjectMethodA)
                               Marshal.GetDelegateForFunctionPointer(JNIEnv_CallObjectMethodA, typeof(SafeHandleDelegate_CallObjectMethodA));
                var safeDel = (SafeHandleDelegate_DeleteLocalRef)
                              Marshal.GetDelegateForFunctionPointer(JNIEnv_DeleteLocalRef, typeof(SafeHandleDelegate_DeleteLocalRef));
                var usafeCall = (IntPtrDelegate_CallObjectMethodA)
                                Marshal.GetDelegateForFunctionPointer(JNIEnv_CallObjectMethodA, typeof(IntPtrDelegate_CallObjectMethodA));
                var usafeDel = (IntPtrDelegate_DeleteLocalRef)
                               Marshal.GetDelegateForFunctionPointer(JNIEnv_DeleteLocalRef, typeof(IntPtrDelegate_DeleteLocalRef));

                var uh   = JniEnvironment.EnvironmentPointer;
                var args = new JniArgumentValue [0];

                sw.Restart();
                for (int i = 0; i < rs.Length; ++i)
                {
                    rs [i] = new JniObjectReference(safeCall(uh, o.Handle, t.ID, args), JniObjectReferenceType.Local);
                }
                sw.Stop();
                safeCallObjectMethodTime = sw.Elapsed;

                sw.Restart();
                for (int i = 0; i < rs.Length; ++i)
                {
                    safeDel(uh, rs [i].Handle);
                    rs [i] = new JniObjectReference();
                }
                sw.Stop();
                safeDeleteLocalRefTime = sw.Elapsed;

                var urs = new IntPtr [MaxLocalRefs];
                var ut  = t.ID;
                var uo  = o.Handle;

                sw.Restart();
                for (int i = 0; i < urs.Length; ++i)
                {
                    urs [i] = usafeCall(uh, uo, ut, args);
                }
                sw.Stop();
                unsafeCallObjectMethodTime = sw.Elapsed;

                sw.Restart();
                for (int i = 0; i < urs.Length; ++i)
                {
                    usafeDel(uh, urs [i]);
                }
                sw.Stop();
                unsafeDeleteLocalRefTime = sw.Elapsed;
            }
        }