歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> haXe NME通過JNI調用Android

haXe NME通過JNI調用Android

日期:2017/3/1 10:03:56   编辑:Linux編程

haXe中的JNI概念

首先澄清一個概念問題,NME中的JNI接口和java中的含義並不相同,java中的JNI是java調用本地C/C++代碼的標准接口,而haXe中的JNI則正好相反,是用haXe在Android目標平台調用java代碼。當然,意義上也說得通,因為從haXe和Android目標的關系來說,Android自帶的java運行庫反而是native的嘛,呵呵。

nme.JNI類的使用

haXe NME調用java方法是通過nme.JNI類實現的,JNI類中只有兩個靜態函數createStaticMethod和createMemberMethod。看看函數的說明:

/**
* Create bindings to an class instance method in Java
* @param className The name of the target class in Java
* @param memberName The name of the target method
* @param signature The JNI string-based type signature for the method
* @param useArray Whether the method should accept multiple parameters, or a single array with the parameters to pass to Java
* @return A method that calls Java. The first parameter is a handle for the Java object instance, the rest are passed into the method as arguments
*/
public static function createMemberMethod(className:String, memberName:String, signature:String, useArray:Bool = false):Dynamic;

/**
* Create bindings to a static class method in Java
* @param className The name of the target class in Java
* @param memberName The name of the target method
* @param signature The JNI string-based type signature for the method
* @param useArray Whether the method should accept multiple parameters, or a single array with the parameters to pass to Java
* @return A method that calls Java. Each argument is passed into the Java method as arguments
*/
public static function createStaticMethod(className:String, memberName:String, signature:String, useArray:Bool = false):Dynamic;

可以看到,參數列表完全一致,這兩個函數的區別就在於,memberMethod在調用時,第一個參數必須是java對象的句柄(handler),它也就是java方法中的this引用。

具體的代碼例子請看下面代碼:

public static function getBuffer():Dynamic
{
if (_getBuffer_func == null)
_getBuffer_func = nme.JNI.createStaticMethod("com/company/product/HaxeStub", "getBuffer", "()[I", true);
var a = new Array<Dynamic>();
return _getBuffer_func(a);
}

上面的haXe函數將調用java類com.company.product.HaxeStub的靜態方法"int[] getBuffer()"。

注意:

1. 類名中的'.'必須用'/'代替,NME自帶的例程中這裡寫錯了(那個例程已經很久沒有更新了)。

2. 所謂signature就是java方法的簽名,也就是方法原型的表述方式,這是Java虛擬機的標准。上面的方法簽名說明getBuffer的原型是int[] getBuffer()。具體細節這裡有篇不錯的文章可以看看http://www.linuxidc.com/Linux/2013-01/77231.htm

3. createStaticMethod返回的Dynamic對象就可以當做一個普通的haXe函數來調用了,haXe會自動幫你對參數和返回值做java <-> haXe的轉換。

4. 如果java方法的返回值是對象類型,你可以獲得該對象的“句柄”(handler),你可以在haXe代碼中傳遞句柄對象,也可以以它為參數調用其它java的靜態方法或成員方法。

5. java類的構造方法也可以被調用,它實際上是作為一個名為"<init>"的普通靜態方法處理的,返回值當然就是創建的新對象的句柄。"<init>"實際上也是構造方法在JVM中的標准名,對應的"<clinit>"則是類的靜態初始化方法的標准名(就是java中 static { ... }這樣的代碼塊,實際也是作為一個java靜態方法處理的)。

Copyright © Linux教程網 All Rights Reserved