public Config() { handle = new Java.Lang.Object( JNIEnv.CreateInstance("com/tapstream/sdk/Config", "()V"), JniHandleOwnership.TransferGlobalRef); cls = JNIEnv.GetObjectClass(handle.Handle); }
public void ValidateDeleteReference(IJavaObject javaObject) { Debug.Assert(javaObject != null); if (javaObject is Class) throw new InvalidOperationException("Cannot delete global reference to 'java.lang.Class' object."); }
private static void TryDispose(this IJavaObject javaObject) { if (!javaObject.IsAlive()) { return; } var hasDefaultConstructor = ObjectToDefaultJavaConstructor .GetOrAdd(javaObject.GetType(), type => { var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, DefaultJavaConstructorArgs, null); if (constructor == null) { if (Tracer.TraceWarning) { Tracer.Warn($"The type {type} cannot be disposed"); } return(false); } return(true); }); if (hasDefaultConstructor) { javaObject.Dispose(); } }
internal static IJavaObject PeekObject(IntPtr handle, Type requiredType = null) { if (handle == IntPtr.Zero) { return(null); } lock (instances) { List <WeakReference> wrefs; if (instances.TryGetValue(JNIEnv.IdentityHash(handle), out wrefs)) { for (int i = 0; i < wrefs.Count; ++i) { var wref = wrefs [i]; IJavaObject res = wref.Target as IJavaObject; if (res != null && res.Handle != IntPtr.Zero && JNIEnv.IsSameObject(handle, res.Handle)) { if (requiredType != null && !requiredType.IsAssignableFrom(res.GetType())) { return(null); } return(res); } } } } return(null); }
public MvxAndroidPropertyChangedListener(INotifyPropertyChanged source, IJavaObject target) : base(source) { if (target == null) throw new ArgumentNullException(nameof(target)); this._target = new WeakReference<IJavaObject>(target); }
internal static IJavaObject JavaCast(IJavaObject instance, Type resultType) { if (resultType == null) { throw new ArgumentNullException("resultType"); } if (instance == null) { return(null); } if (resultType.IsAssignableFrom(instance.GetType())) { return(instance); } if (resultType.IsClass) { return(CastClass(instance, resultType)); } else if (resultType.IsInterface) { return(Java.Lang.Object.GetObject(instance.Handle, JniHandleOwnership.DoNotTransfer, resultType)); } else { throw new NotSupportedException(string.Format("Unable to convert type '{0}' to '{1}'.", instance.GetType().FullName, resultType.FullName)); } }
internal static TResult _JavaCast <TResult> (this IJavaObject instance) { if (instance == null) { return(default(TResult)); } if (instance is TResult) { return((TResult)instance); } Type resultType = typeof(TResult); if (resultType.IsClass) { return((TResult)CastClass(instance, resultType)); } else if (resultType.IsInterface) { Type invokerType = GetHelperType(resultType, "Invoker"); if (invokerType == null) { throw new ArgumentException("Unable to get Invoker for interface '" + resultType.FullName + "'.", "TResult"); } Func <IntPtr, JniHandleOwnership, TResult> getObject = (Func <IntPtr, JniHandleOwnership, TResult>)Delegate.CreateDelegate(typeof(Func <IntPtr, JniHandleOwnership, TResult>), invokerType, "GetObject"); return(getObject(instance.Handle, JniHandleOwnership.DoNotTransfer)); } else { throw new NotSupportedException(string.Format("Unable to convert type '{0}' to '{1}'.", instance.GetType().FullName, resultType.FullName)); } }
internal static TResult _JavaCast <TResult> (this IJavaObject instance) { if (instance == null) { return(default(TResult)); } if (instance is TResult) { return((TResult)instance); } Type resultType = typeof(TResult); if (resultType.IsClass) { return((TResult)CastClass(instance, resultType)); } else if (resultType.IsInterface) { return((TResult)Java.Lang.Object.GetObject(instance.Handle, JniHandleOwnership.DoNotTransfer, resultType)); } else { throw new NotSupportedException(string.Format("Unable to convert type '{0}' to '{1}'.", instance.GetType().FullName, resultType.FullName)); } }
static IJavaObject CastClass(IJavaObject instance, Type resultType) { var klass = JNIEnv.FindClass(resultType); try { if (klass == IntPtr.Zero) { throw new ArgumentException("Unable to determine JNI class for '" + resultType.FullName + "'.", "TResult"); } if (!JNIEnv.IsInstanceOf(instance.Handle, klass)) { throw new InvalidCastException( string.Format("Unable to convert instance of type '{0}' to type '{1}'.", instance.GetType().FullName, resultType.FullName)); } } finally { JNIEnv.DeleteGlobalRef(klass); } if (resultType.IsAbstract) { // TODO: keep in sync with TypeManager.CreateInstance() algorithm Type invokerType = GetHelperType(resultType, "Invoker"); if (invokerType == null) { throw new ArgumentException("Unable to get Invoker for abstract type '" + resultType.FullName + "'.", "TResult"); } resultType = invokerType; } return((IJavaObject)TypeManager.CreateProxy(resultType, instance.Handle, JniHandleOwnership.DoNotTransfer)); }
public Event(string name, bool oneTimeOnly) { handle = new Java.Lang.Object( JNIEnv.CreateInstance("com/tapstream/sdk/Event", "(Ljava/lang/String;Z)V", new JValue(new Java.Lang.String(name)), new JValue(oneTimeOnly)), JniHandleOwnership.TransferGlobalRef); addPairId = JNIEnv.GetMethodID(JNIEnv.GetObjectClass(handle.Handle), "addPair", "(Ljava/lang/String;Ljava/lang/Object;)V"); }
public static T GetOrCreateMediator <T>(this IJavaObject item, ref T mediator) where T : class { if (mediator == null) { Interlocked.CompareExchange(ref mediator, (T)MediatorFactory(item, DataContext.Empty, typeof(T)), null); } return(mediator); }
public MvxAndroidPropertyChangedListener(INotifyPropertyChanged source, IJavaObject target) : base(source) { if (target == null) { throw new ArgumentNullException(nameof(target)); } _target = new WeakReference <IJavaObject>(target); }
internal static void RegisterInstance(IJavaObject instance, IntPtr value, JniHandleOwnership transfer, out IntPtr handle) { if (value == IntPtr.Zero) { handle = value; return; } var transferType = transfer & (JniHandleOwnership.DoNotTransfer | JniHandleOwnership.TransferLocalRef | JniHandleOwnership.TransferGlobalRef); switch (transferType) { case JniHandleOwnership.DoNotTransfer: handle = JNIEnv.NewGlobalRef(value); break; case JniHandleOwnership.TransferLocalRef: handle = JNIEnv.NewGlobalRef(value); JNIEnv.DeleteLocalRef(value); break; case JniHandleOwnership.TransferGlobalRef: handle = value; break; default: throw new ArgumentOutOfRangeException("transfer", transfer, "Invalid `transfer` value: " + transfer + " on type " + instance.GetType()); } if (handle == IntPtr.Zero) { throw new InvalidOperationException("Unable to allocate Global Reference for object '" + instance.ToString() + "'!"); } IntPtr key = JNIEnv.IdentityHash(handle); if ((transfer & JniHandleOwnership.DoNotRegister) == 0) { _RegisterInstance(instance, key, handle); } var ex = instance as IJavaObjectEx; if (ex != null) { ex.KeyHandle = key; } if (Logger.LogGlobalRef) { JNIEnv._monodroid_gref_log("handle 0x" + handle.ToString("x") + "; key_handle 0x" + key.ToString("x") + ": Java Type: `" + JNIEnv.GetClassNameFromInstance(handle) + "`; " + "MCW type: `" + instance.GetType().FullName + "`\n"); } }
/// <summary> /// 将 <see cref="IJavaObject"/> 转换为泛型类型,常用于修复绑定库中泛型丢失导致的问题 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static T Cast <T>(this IJavaObject obj) { if (obj is T t) { return(t); } else { var msg = $"Java generic binding conversion failed, obj_type: {obj?.GetType()}, t_type: {typeof(T)}."; throw new InvalidCastException(msg); } }
public static IDictionary FromJniHandle (IntPtr handle, JniHandleOwnership transfer) { if (handle == IntPtr.Zero) return null; IJavaObject inst = (IJavaObject) Java.Lang.Object.PeekObject (handle); if (inst == null) inst = new JavaDictionary (handle, transfer); else JNIEnv.DeleteRef (handle, transfer); return (IDictionary) inst; }
public static Value ConvertToValue(object o) { if (o == null) { return(Value.Null); } IJavaObject i = o as IJavaObject; Value ret = new Value(); ret._object = i.JvmHandle; return(ret); }
private static WeakReference CreateWeakReference(object item, IJavaObject javaItem, bool isWeakTable) { if (javaItem == null) { if (isWeakTable) { return(new WeakReferenceWeakTable(item)); } return(new WeakReference(item, true)); } if (isWeakTable) { return(new JavaObjectWeakReferenceWeakTable(javaItem)); } return(new JavaObjectWeakReference(javaItem)); }
public override void Execute() { ImportPackage("java.lang"); ImportPackage("java.util"); ImportPackage("java.awt"); var listener = new CLRActionListener(ActionDone); InitializeListener(listener); var frame = DynJVM.Frame.@new("AWT GUI"); frame.setSize(300, 300); textArea = DynJVM.TextArea.@new(); buttonWrite = DynJVM.Button.@new("Write to console"); buttonWrite.setActionCommand("writeToConsole"); buttonWrite.addActionListener(listener.DynListener); var buttonTextAreaWrite = DynJVM.Button.@new("Write TextArea to console"); buttonTextAreaWrite.setActionCommand("writeTextAreaToConsole"); buttonTextAreaWrite.addActionListener(listener.DynListener); var buttonClose = DynJVM.Button.@new("Close application"); buttonClose.setActionCommand("closeApplication"); buttonClose.addActionListener(listener.DynListener); var panel = DynJVM.Panel.@new(); var layout = DynJVM.GridLayout.@new(2, 2); panel.setLayout(layout); panel.add(textArea); panel.add(buttonTextAreaWrite); panel.add(buttonWrite); // Adds Button to content pane of frame panel.add(buttonClose); // Adds Button to content pane of frame frame.add(panel); frame.setVisible(true); Console.WriteLine("Waiting for close..."); while (execute) { System.Threading.Thread.Sleep(10); } buttonWrite.removeActionListener(listener.DynListener); buttonClose.removeActionListener(listener.DynListener); ReleaseListener(listener); }
static void _RegisterInstance(IJavaObject instance, IntPtr key, IntPtr handle) { lock (instances) { List <WeakReference> wrefs; if (!instances.TryGetValue(key, out wrefs)) { wrefs = new List <WeakReference> (1) { new WeakReference(instance, true), }; instances.Add(key, wrefs); } else { bool found = false; for (int i = 0; i < wrefs.Count; ++i) { var wref = wrefs [i]; if (ShouldReplaceMapping(wref, handle)) { found = true; wrefs.Remove(wref); wrefs.Add(new WeakReference(instance, true)); break; } var cur = wref == null ? null : (IJavaObject)wref.Target; var _c = cur == null ? IntPtr.Zero : cur.Handle; if (_c != IntPtr.Zero && JNIEnv.IsSameObject(handle, _c)) { found = true; if (Logger.LogGlobalRef) { Logger.Log(LogLevel.Info, "monodroid-gref", string.Format("warning: not replacing previous registered handle 0x{0} with handle 0x{1} for key_handle 0x{2}", _c.ToString("x"), handle.ToString("x"), key.ToString("x"))); } break; } } if (!found) { wrefs.Add(new WeakReference(instance, true)); } } } }
public static T FromJniHandle <T>(IntPtr handle, JniHandleOwnership transfer, out bool set) { if (handle == IntPtr.Zero) { set = false; return(default(T)); } IJavaObject interned = (IJavaObject)Java.Lang.Object.PeekObject(handle); if (interned != null) { T r = FromJavaObject <T>(interned, out set); if (set) { JNIEnv.DeleteRef(handle, transfer); return(r); } } set = true; if (typeof(IJavaObject).IsAssignableFrom(typeof(T))) { return((T)Java.Lang.Object._GetObject <T> (handle, transfer)); } Func <IntPtr, JniHandleOwnership, object> converter = GetJniHandleConverter(typeof(T)) ?? GetJniHandleConverter(GetTypeMapping(handle)); if (converter != null) { return((T)converter(handle, transfer)); } var v = Java.Lang.Object.GetObject(handle, transfer); if (v is T) { return((T)v); } // hail mary pass; perhaps there's a MCW which participates in normal // .NET type conversion? return((T)Convert.ChangeType(v, typeof(T))); }
public static T FromJavaObject <T>(IJavaObject value, out bool set) { if (value == null) { set = false; return(default(T)); } if (typeof(IJavaObject).IsAssignableFrom(typeof(T))) { set = true; return(value._JavaCast <T>()); } var o = value as JavaObject; if (o != null) { set = true; if (o.Instance is T) { return((T)o.Instance); } return((T)Convert.ChangeType(o.Instance, typeof(T))); } if (value is T) { set = true; return((T)value); } IntPtr lrefValue = JNIEnv.ToLocalJniHandle(value); if (lrefValue == IntPtr.Zero) { set = false; return(default(T)); } set = true; Func <IntPtr, JniHandleOwnership, object> converter = GetJniHandleConverter(typeof(T)); if (converter != null) { return((T)converter(lrefValue, JniHandleOwnership.TransferLocalRef)); } JNIEnv.DeleteLocalRef(lrefValue); return((T)Convert.ChangeType(value, typeof(T))); }
static XmlReader FromNative(IntPtr handle, JniHandleOwnership transfer) { if (handle == IntPtr.Zero) { return(null); } IJavaObject inst = Java.Lang.Object.PeekObject(handle); if (inst == null) { inst = Java.Interop.TypeManager.CreateInstance(handle, transfer); } else { JNIEnv.DeleteRef(handle, transfer); } return(new XmlPullParserReader(inst.JavaCast <IXmlPullParser> ())); }
public static object FromJniHandle(IntPtr handle, JniHandleOwnership transfer, Type targetType = null) { if (handle == IntPtr.Zero) { return(null); } IJavaObject interned = (IJavaObject)Java.Lang.Object.PeekObject(handle); if (interned != null) { var unwrapped = FromJavaObject(interned, targetType); if (unwrapped != null) { JNIEnv.DeleteRef(handle, transfer); return(unwrapped); } } if (targetType != null && typeof(IJavaObject).IsAssignableFrom(targetType)) { return(Java.Lang.Object.GetObject(handle, transfer, targetType)); } Func <IntPtr, JniHandleOwnership, object> converter = targetType != null ? (GetJniHandleConverter(targetType) ?? GetJniHandleConverter(GetTypeMapping(handle))) : GetJniHandleConverter(GetTypeMapping(handle)); if (converter != null) { return(converter(handle, transfer)); } var v = Java.Lang.Object.GetObject(handle, transfer); if (v != null && (targetType == null || targetType.IsAssignableFrom(v.GetType()))) { return(v); } // hail mary pass; perhaps there's a MCW which participates in normal // .NET type conversion? return(Convert.ChangeType(v, targetType)); }
public static TReturn WithLocalJniHandle <TValue, TReturn>(TValue value, Func <IntPtr, TReturn> action) { IntPtr lref = IntPtr.Zero; try { IJavaObject v = value as IJavaObject; if (v != null) { lref = JNIEnv.ToLocalJniHandle(v); return(action(lref)); } Func <object, IntPtr> converter = GetLocalJniHandleConverter(value, typeof(TValue)); lref = converter(value); return(action(lref)); } finally { JNIEnv.DeleteLocalRef(lref); } }
public override void Execute() { double a = 2; double b = 3; double c = Math.PI / 2; ImportPackage("JavaClass"); IJavaObject javaClass = JVM.New("JavaClass") as IJavaObject; IJavaObject res = (IJavaObject)javaClass.Invoke("helloWorld"); //string shall be converted because is not a native string hello = (string)res.ToPrimitive(); double result = (double)javaClass.Invoke("add", a, b); double sin = (double)javaClass.Invoke("sin", c); Console.WriteLine("{0} {1} + {2} = {3} and sin({4:0.0000000}) = {5:0.00000000}", hello, a, b, result, c, sin); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); }
public static object FromJavaObject(IJavaObject value, Type targetType = null) { if (value == null) { return(null); } if (targetType != null && typeof(IJavaObject).IsAssignableFrom(targetType)) { return(JavaObjectExtensions.JavaCast(value, targetType)); } var o = value as JavaObject; if (o != null) { if (targetType == null) { return(o.Instance); } return(Convert.ChangeType(o.Instance, targetType)); } if (targetType == null || targetType.IsAssignableFrom(value.GetType())) { return(value); } IntPtr lrefValue = JNIEnv.ToLocalJniHandle(value); if (lrefValue == IntPtr.Zero) { return(null); } Func <IntPtr, JniHandleOwnership, object> converter = GetJniHandleConverter(targetType); if (converter != null) { return(converter(lrefValue, JniHandleOwnership.TransferLocalRef)); } JNIEnv.DeleteLocalRef(lrefValue); return(Convert.ChangeType(value, targetType)); }
public static ICollection FromJniHandle(IntPtr handle, JniHandleOwnership transfer) { if (handle == IntPtr.Zero) { return(null); } IJavaObject inst = Java.Lang.Object.PeekObject(handle); if (inst == null) { inst = new JavaCollection(handle, transfer); } else { JNIEnv.DeleteRef(handle, transfer); } return((ICollection)inst); }
internal static Stream FromNative(IntPtr handle, JniHandleOwnership transfer) { if (handle == IntPtr.Zero) { return(null); } IJavaObject inst = Java.Lang.Object.PeekObject(handle); if (inst == null) { inst = Java.Interop.TypeManager.CreateInstance(handle, transfer); } else { JNIEnv.DeleteRef(handle, transfer); } return(new OutputStreamInvoker((Java.IO.OutputStream)inst)); }
internal static IJavaObject JavaCast(IJavaObject instance, Type resultType) { if (resultType == null) { throw new ArgumentNullException("resultType"); } if (instance == null) { return(null); } if (resultType.IsAssignableFrom(instance.GetType())) { return(instance); } if (resultType.IsClass) { return(CastClass(instance, resultType)); } else if (resultType.IsInterface) { Type invokerType = GetHelperType(resultType, "Invoker"); if (invokerType == null) { throw new ArgumentException("Unable to get Invoker for interface '" + resultType.FullName + "'.", "resultType"); } var getObject = invokerType.GetMethod("GetObject", new[] { typeof(IntPtr), typeof(JniHandleOwnership) }); return((IJavaObject)getObject.Invoke(null, new object[] { instance.Handle, JniHandleOwnership.DoNotTransfer })); } else { throw new NotSupportedException(string.Format("Unable to convert type '{0}' to '{1}'.", instance.GetType().FullName, resultType.FullName)); } }
public JValue (IJavaObject value) { this = new JValue (); l = value == null ? IntPtr.Zero : value.Handle; }
public static TResult JavaCast <TResult> (this IJavaObject instance) where TResult : class, IJavaObject { return(_JavaCast <TResult> (instance)); }
static void _RegisterInstance(IJavaObject instance, IntPtr key, IntPtr handle) { throw new NotImplementedException(); }
public JavaObjectWeakReferenceWeakTable(IJavaObject item) : base(item) { _hash = RuntimeHelpers.GetHashCode(item); }
public IJavaObject invoke(IJavaObject arg0, ObjectArray<IJavaObject> arg1) { return Instance.CallMethod<IJavaObject>("invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", arg0, arg1); }
public AssertionError(IJavaObject arg0) : base(ProxyCtor.I) { Instance.CallConstructor("(Ljava/lang/Object;)V", arg0); }
public StringBuilder insert(int arg0, IJavaObject arg1) { return Instance.CallMethod<StringBuilder>("insert", "(ILjava/lang/Object;)Ljava/lang/StringBuilder;", arg0, arg1); }
public void notifyObservers(IJavaObject arg0) { Instance.CallMethod("notifyObservers", "(Ljava/lang/Object;)V", arg0); }
public static int identityHashCode(IJavaObject arg0) { return Static.CallMethod<int>(typeof(System), "identityHashCode", "(Ljava/lang/Object;)I", arg0); }
public IJavaObject attach(IJavaObject arg0) { return Instance.CallMethod<IJavaObject>("attach", "(Ljava/lang/Object;)Ljava/lang/Object;", arg0); }
public void println(IJavaObject arg0) { Instance.CallMethod("println", "(Ljava/lang/Object;)V", arg0); }
public void addAttribute(AttributedCharacterIterator_.Attribute arg0, IJavaObject arg1) { Instance.CallMethod("addAttribute", "(Ljava/text/AttributedCharacterIterator/Attribute;Ljava/lang/Object;)V", arg0, arg1); }
public String format(IJavaObject arg0) { return Instance.CallMethod<String>("format", "(Ljava/lang/Object;)Ljava/lang/String;", arg0); }
public StringBuilder append(IJavaObject arg0) { return Instance.CallMethod<StringBuilder>("append", "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", arg0); }
public void put(String arg0, IJavaObject arg1) { Instance.CallMethod("put", "(Ljava/lang/String;Ljava/lang/Object;)V", arg0, arg1); }
public StringBuffer format(IJavaObject arg0, StringBuffer arg1, FieldPosition arg2) { return Instance.CallMethod<StringBuffer>("format", "(Ljava/lang/Object;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0, arg1, arg2); }
public GremlinScript(IJavaObject javaObject) { _sb.Append(javaObject.ToString()); }
public void logrb(Level arg0, String arg1, String arg2, String arg3, String arg4, IJavaObject arg5) { Instance.CallMethod("logrb", "(Ljava/util/logging/Level;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V", arg0, arg1, arg2, arg3, arg4, arg5); }
public static void IsValidJavaObject(IJavaObject javaObject) { IsValidJavaProxy((IJavaProxy)javaObject); }
public JavaObjectWeakReference(IJavaObject item) : base(item) { }
public EventObject(IJavaObject arg0) : base(ProxyCtor.I) { Instance.CallConstructor("(Ljava/lang/Object;)V", arg0); }
internal static void RegisterInstance(IJavaObject instance, IntPtr value, JniHandleOwnership transfer, out IntPtr handle) { throw new NotImplementedException(); }
public void writeUnshared(IJavaObject arg0) { Instance.CallMethod("writeUnshared", "(Ljava/lang/Object;)V", arg0); }
public static void arraycopy(IJavaObject arg0, int arg1, IJavaObject arg2, int arg3, int arg4) { Static.CallMethod(typeof(System), "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", arg0, arg1, arg2, arg3, arg4); }
public AttributedCharacterIterator formatToCharacterIterator(IJavaObject arg0) { return Instance.CallMethod<AttributedCharacterIterator>("formatToCharacterIterator", "(Ljava/lang/Object;)Ljava/text/AttributedCharacterIterator;", arg0); }
public void exiting(String arg0, String arg1, IJavaObject arg2) { Instance.CallMethod("exiting", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V", arg0, arg1, arg2); }
public static IJavaObject command(IJavaObject arg0) { return Static.CallMethod<IJavaObject>(typeof(Compiler), "command", "(Ljava/lang/Object;)Ljava/lang/Object;", arg0); }
public void log(Level arg0, String arg1, IJavaObject arg2) { Instance.CallMethod("log", "(Ljava/util/logging/Level;Ljava/lang/String;Ljava/lang/Object;)V", arg0, arg1, arg2); }
public void setOption(int arg0, IJavaObject arg1) { Instance.CallMethod("setOption", "(ILjava/lang/Object;)V", arg0, arg1); }