我想使用SWIG在Java和C ++之间传递一段信息(例如1024字节的内存)。 C ++中定义的结构如下:
struct Buffer
{
unsigned char *addr;
size_t size;
}
我应该如何为此目的编写SWIG接口文件?
答案 0 :(得分:1)
目前还不完全清楚你想要达到的目的。
如果您想将Buffer
映射到Java byte[]
,可以使用自定义类型映射进行映射:
%typemap(jni) Buffer "jbyteArray"
%typemap(jtype) Buffer "byte[]"
%typemap(jstype) Buffer "byte[]"
%typemap(in) Buffer {
$1.addr = (unsigned char *) JCALL2(GetByteArrayElements, jenv, $input, 0);
$1.size = JCALL1(GetArrayLength, jenv, $input);
}
%typemap(argout) Buffer {
JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *) $1.addr, 0);
}
%typemap(out) Buffer {
$result = JCALL1(NewByteArray, jenv, $1.size);
JCALL4(SetByteArrayRegion, jenv, $result, 0, $1.size, (jbyte *) $1.addr);
delete[] $1.addr;
}
%typemap(javain) Buffer "$javainput"
%typemap(javaout) Buffer { return $jnicall; }
然后是C ++代码,如
Buffer getData();
void sendData(Buffer arg);
将映射到Java:
public static byte[] getData() { ... }
public static void sendData(byte[] arg) { ... }
将数据传递给Java的难点在于将其传入JVM堆和/或管理数据的生命周期。通过一些复制很容易实现,但真正的0副本解决方案通常需要更改C ++接口。
完整示例:
<强> example.h文件强>
#include <stddef.h>
struct Buffer
{
unsigned char *addr;
size_t size;
};
Buffer getData();
void sendData(Buffer);
<强> example.cxx 强>
#include "example.h"
Buffer getData() {
Buffer rc { new unsigned char[64], 64 };
for (int i = 0; i < rc.size; ++i)
rc.addr[i] = 0x40 + i;
return rc;
}
void sendData(Buffer buf) {
// use buf.addr
}
<强> example.i 强>
%module example
%{
#include "example.h"
%}
%typemap(jni) Buffer "jbyteArray"
%typemap(jtype) Buffer "byte[]"
%typemap(jstype) Buffer "byte[]"
%typemap(in) Buffer {
$1.addr = (unsigned char *) JCALL2(GetByteArrayElements, jenv, $input, 0);
$1.size = JCALL1(GetArrayLength, jenv, $input);
}
%typemap(argout) Buffer {
JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *) $1.addr, 0);
}
%typemap(out) Buffer {
$result = JCALL1(NewByteArray, jenv, $1.size);
JCALL4(SetByteArrayRegion, jenv, $result, 0, $1.size, (jbyte *) $1.addr);
delete[] $1.addr;
}
%typemap(javain) Buffer "$javainput"
%typemap(javaout) Buffer { return $jnicall; }
%ignore Buffer;
%include "example.h"
<强> test.java 强>
class test {
public static void main(String[] args) throws Exception {
System.loadLibrary("_example");
byte[] data = example.getData();
System.out.println(new String(data));
}
}
<强>输出强>:
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂