SWIG引用类型

2023-05-16

  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);
}
}




本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SWIG引用类型 的相关文章

随机推荐