1

我想使用 swig 创建一个 JNI 接口,而不是 C++ 函数存在的常见方式。我想添加一个带有 java 类参数的方法/函数。

文件:test.i

%typemap(javaimports) A %{
import java.awt.Component;
%}

%extend(java) A {
  void Attach( Component awt)
  {
    // here I Want to retrieve XDisplay, Window, Screen from 
    // /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64/include/jawt.h
    // I need canvas of type jobject.
    // with this information I call Attach( XDisplay * dpy, Window win);
  }
}

class A
{
public:
   void Attach( XDisplay * dpy, Window win);
};
4

1 回答 1

0

您需要一些类型映射才能将其java.awt.Component传递给扩展方法jobject

%module test

%typemap(jstype) jobject *awtcomponent "java.awt.Component";
%typemap(jtype) jobject *awtcomponent "java.awt.Component";
%typemap(jni) jobject *awtcomponent "jobject";
%typemap(javain) jobject *awtcomponent "$javainput";

%extend A {
  void attach(jobject awtcomponent) {
    // Call whatever JNI functions you want with this jobject 
    // (which is always an AWT component)

    // Then:
    $self->Attach(arg1, arg2);
  }
}

%inline %{
struct A {
};
%}

鉴于您已经有一个成员函数,您实际上可以%extend完全跳过并使用类型映射直接处理它:

%module test
%typemap(jstype) (XDisplay * dpy, Window win)  "java.awt.Component";
%typemap(jtype) (XDisplay * dpy, Window win) "java.awt.Component";
%typemap(jni) (XDisplay * dpy, Window win) "jobject";
%typemap(javain) (XDisplay * dpy, Window win)  "$javainput";

%typemap(in,numinputs=1) (XDisplay * dpy, Window win) {
  // some JNI to convert $input (jobject) into $1 (dpy) and $2 (win)
}

%inline %{
struct A {
  void Attach(XDisplay * dpy, Window win) {}
};
%}

这些类型映射具有额外的好处,可以在您拥有的任何地方工作XDisplayWindow无需额外努力即可配对。

完整的示例源自jawt.h 示例,并填写了所有JNI:

%module test

%{
#include <X11/Xlib.h>
#include <jawt.h>
#include <jawt_md.h>
#include <cassert>
%}

%typemap(jstype) (Display * dpy, Window win)  "java.awt.Component";
%typemap(jtype) (Display * dpy, Window win) "java.awt.Component";
%typemap(jni) (Display * dpy, Window win) "jobject";
%typemap(javain) (Display * dpy, Window win)  "$javainput";

%typemap(in,noblock=1,numinputs=1) (Display * dpy, Window win) {
  // some JNI to convert $input (jobject) into $1 (dpy) and $2 (win)
  JAWT awt;
  JAWT_DrawingSurface* ds;
  JAWT_DrawingSurfaceInfo *dsi;
  JAWT_X11DrawingSurfaceInfo* dsi_x11;
  jboolean result;
  jint lock;

  awt.version = JAWT_VERSION_1_3;
  result = JAWT_GetAWT(jenv, &awt);
  assert(result != JNI_FALSE);

  ds = awt.GetDrawingSurface(jenv, $input);
  assert(ds != NULL);

  lock = ds->Lock(ds);
  assert((lock & JAWT_LOCK_ERROR) == 0);

  dsi = ds->GetDrawingSurfaceInfo(ds);
  dsi_x11 = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;
  $1 = dsi_x11->display;
  $2 = dsi_x11->drawable;
}

%typemap(freearg) (Display * dpy, Window win) {
  ds->FreeDrawingSurfaceInfo(dsi);
  ds->Unlock(ds);
  awt.FreeDrawingSurface(ds);
}

%inline %{
struct A {
  void Attach(Display * dpy, Window win) {}
};
%}

两个显着的变化是添加的 freearg 类型映射,它在调用 cleanup 之后运行,以及noblock=1使本地临时变量对 freearg 可见。

于 2013-08-06T19:03:21.567 回答