Swig typemap java对象 [英] Swig typemap java object
问题描述
我试图通过swig为这两个c ++函数生成java绑定
I am trying to generate java bindings through swig for these two c++ functions
C ++函数
void SetUserData(void* data);
void* GetUserData() const;
在java方面,我希望它看起来像这样
On the java side I want it to look like this
setUserData(Object object);
getUserData() //return java.lang.Object
我想要无效*指向我传递给它的任何java对象的指针。在我的swig文件中,我尝试添加这些行
I would like the void* pointer to point to any java object I pass to it. In my swig file I tried to add these lines
//swig file
%typemap(jstype) void* "java.lang.Object";
%apply Object {void*};
我收到编译错误:
b2Fixture.swig(22):警告453:可以不适用(对象)。没有定义任何类型图。我不知道如何为此制作打字机。有什么想法?
I get a compile error: b2Fixture.swig(22) : Warning 453: Can't apply (Object). No typemaps are defined. I have no idea how to make typemaps for this. Any ideas?
推荐答案
您可能想这样做:
%apply jobject { void* };
因为%apply将在一个C ++类型上定义的类型映射复制到另一个C ++类型。 Object
是Java类型,而不是C ++类型,因此没有要复制的任何类型地图。另一方面, jobject
是等效的JNI。
because %apply copies the typemaps defined on one C++ type to another C++ type. Object
is a Java type, not a C++ one so doesn't have any typemaps to be copied. jobject
on the other hand is the JNI equivalent.
另外假设你想要'正常'的GC语义(即不需要保留您传递的任何数据)您需要做更多的工作,例如:
Additionally assuming you want to have 'normal' GC semantics (i.e. not be required to retain whatever data you pass in) you'll need to do some more work, for example:
%module test
%{
#include "test.hh"
%}
%apply jobject { void * };
%typemap(in) void * {
void *old = getData();
if (old) JCALL1(DeleteGlobalRef, jenv, (jobject)old);
$1 = JCALL1(NewGlobalRef, jenv, $input);
}
%typemap(out) void * {
$result = (jobject)($1);
}
%include "test.hh"
这为您的数据创建一个新的全局参考,这可能是唯一阻止它被GC释放的东西。
This makes a new Global Reference for your data, which could be the only thing keeping it from getting freed by the GC.
给定一个头文件:
void setData(void *);
void *getData();
和实施:
#include "test.hh"
namespace {
void *d = nullptr;
}
void setData(void *d) {
::d = d;
}
void *getData() {
return d;
}
这足以允许:
public class run {
public static void main(String[] argv) {
System.loadLibrary("test");
Object example = "HELLO";
test.setData(example);
System.out.println(test.getData());
}
}
正常工作。
如上所述,这些类型地图非常难看 - 它们会影响所有 c> void * 的使用。因此,如果你真的使用了这个,你会想要第二次使用%apply
或%clear
来限制它们的影响。您还可以在头文件中命名参数,并使用它来限制应用typemap的位置。
As written these typemaps are pretty ugly - they'll impact all usage of void *
. So if you really used this you would want to use %apply
or %clear
a second time to limit their impact. You could also name the arguments in the header file and use that to limit where the typemap gets applied.
这篇关于Swig typemap java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!