SWIG引用类型
? SWIG也提供支持指針。SWIG存儲指針使用long數據類型。通過使用fianlize函數管理與Java類相關聯的c組件的生命周期。
? ?C++代碼的封裝:
? 在上一部分,你瀏覽了C封裝組件的基本。現在你將集中封裝C++代碼。首先,需要修改Android.mk文件來命令SWIG來產生C++代碼。
??MY_SWIG_PACKAGE := com.apress.swig
? MY_SWIG_INTERFACES := Unix.i
? MY_SWIG_TYPE := cxx
?指針,引用和值
在C/C++,函數的參數有多重形式,如指針,引用或者通過簡單的值。
/* By pointer. */
void drawByPointer(struct Point* p);
/* By reference */
void drawByReference(struct Point& p);
/* By value. */
void drawByValue(struct Point p);
在Java中沒有這樣的類型。SWIG將統一這些類型為對象實例引用,如下:
package com.apress.swig;
public class Unix implements UnixConstants {
. . .
public static void drawByPointer(Point p) {
UnixJNI.drawByPointer(Point.getCPtr(p), p);
}
public static void drawByReference(Point p) {
UnixJNI.drawByReference(Point.getCPtr(p), p);
}
public static void drawByValue(Point p) {
UnixJNI.drawByValue(Point.getCPtr(p), p);
}
默認參數
盡管默認參數,Java是不支持的,SWIG支持帶有默認參數的函數通過產生對于每個默認參數的額外的函數。如下:
%module Unix
. . .
/* Function with default arguments. */
void func(int a = 1, int b = 2, int c = 3);
package com.apress.swig;
public class Unix {
. . .
public static void func(int a, int b, int c) {
UnixJNI.func__SWIG_0(a, b, c);
}
public static void func(int a, int b) {
UnixJNI.func__SWIG_1(a, b);
}
public static void func(int a) {
UnixJNI.func__SWIG_2(a);
}
public static void func() {
UnixJNI.func__SWIG_3();
}
}
函數的重載:
SWIG很容易的支持重載函數因為Java已經對他們提供了支持。重載函數被定義在接口文件中,如下:
%module Unix
. . .
/* Overloaded functions. */
void func(double d);
void func(int i);
package com.apress.swig;
public class Unix {
. . .
public static void func(double d) {
UnixJNI.func__SWIG_0(d);
}
public static void func(int i) {
UnixJNI.func__SWIG_1(i);
}
}
SWIG解決重載函數使用沒有異議的模式,就是排名和排序定義依據一套類型規則。除了函數和原始的類型外,SWIG也能夠支持C++的類。
. .
class A {
public:
A();
A(int value);
~A();
void print();
int value;
private:
void reset();
};
SWIG產生相應的Java類,如下。值成員變量時共有的,和其相應的getter和setter函數時有Swig自動產生的。這個reset方法并不能傳遞給Java,因為它被定義為私有的在類的定義中。
public class A {
private long swigCPtr;
protected boolean swigCMemOwn;
Download at http://www.pin5i.com/
121 CHAPTER 4: Auto-Generate JNI Code Using SWIG?
protected A(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(A obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr ! = 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
UnixJNI.delete_A(swigCPtr);
}
swigCPtr = 0;
}
}
public A() {
this(UnixJNI.new_A__SWIG_0(), true);
}
public A(int value) {
this(UnixJNI.new_A__SWIG_1(value), true);
}
public void print() {
UnixJNI.A_print(swigCPtr, this);
}
public void setValue(int value) {
UnixJNI.A_value_set(swigCPtr, this, value);
}
public int getValue() {
return UnixJNI.A_value_get(swigCPtr, this);
}
}
總結