On Mar 19, 2012, at 8:56 PM, GavinBryan wrote:
> I'm trying to make a call from c# to a Java library and can't figure out the
> bits of JNIENV syntax
You're on the right track... :-)
> // This is the Java call I'm trying to make in C#
> String apid = PushManager.shared().getAPID();
> IntPtr ipPushmanager = JNIEnv.FindClass("com/urbanairship/push/PushManager");
> IntPtr ipShared = JNIEnv.GetStaticMethodID(ipPushmanager , "shared",
> "()Lcom/urbanairship/push/PushManager;");
These are both correct.
> IntPtr ipApid = JNIEnv.GetMethodID(?????, "getAPID", "()Ljava.lang.String;");
The getAPID() method is an instance method on com.urbanairship.push.PushManager
(as that's the type that PushManager.shared() returns). Conveniently enough,
this is also a type you already looked up. You do need to fix the signature
though:
IntPtr ipApid = JNIEnv.GetMethodID(ipPushmanager, "getAPID",
"()Ljava/lang/String");
Which leaves invocation:
IntPtr sharedInstance = JNIEnv.CallStaticObjectMethod(ipPushmanager,
ipShared);
var apid = Java.Lang.Object.GetObject<Java.Lang.String>(
JNIEnv.CallObjectMethod(sharedInstance, ipApid),
JniHandleOwnership.TransferLocalRef);
// Not necessarily necessary, but a good practice
JNIEnv.DeleteLocalRef(sharedInstance);
Method invocation is done by one of the JNIEnv.CallStaticXxxMethod() or
JNIEnv.CallXxxMethod() methods; Xxx depends on the return type of the method,
and CallStatic XxxMethod() is for static methods while CallXxxMethod() is for
instance methods. Thus we use JNIEnv.CallStaticObjectMethod() to invoke the
PushManager.shared() static method (as it returns a java.lang.Object subclass),
and we use JNIEnv.CallObjectMethod() to invoke the PushManager.getAPID()
instance method (which likewise returns a java.lang.Object subclass).
Finally we convert the value returned from JNIEnv.CallObjectMethod() into a
Java.Lang.String instance by using the Java.Lang.Object.GetObject<T>(IntPtr,
JniHandleOwnership) method, which returns a value of type `T`. The
JniHandleOwnership parameter specifies what kind of JNI handle the value is; in
this case, it's a local ref (as that's what all JNIEnv.Call*ObjectMethod()
methods return).
As the comment suggests, JNIEnv.DeleteLocalRef(sharedInstance) _may_ not be
necessary. The local reference table is limited to only 512 entries, but it's
cleared upon returning to Dalvik code. If your method is short, it's _probably_
fine to skip this, but "better safe than sorry."
- Jon
_______________________________________________
Monodroid mailing list
[email protected]
UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid