// Example A: Returns a C string directly
const char* getString();
// Example B: Returns a wide character C string directly
const wchar_t* getString();
一般情况下,如果是native方法直接返回string,我们可以使用String进行映射:
// Mapping A
String getString();
// Mapping B
WString getString();
public static class TestPointerType extends PointerType {
public TestPointerType() { }
public TestPointerType(Pointer p) { super(p); }
}
TestPointerType returnPointerArrayElement(TestPointerType[] args, int which);
再看一下字符串数组:
char* returnStringArrayElement(char* args[], int which) {
return args[which];
}
wchar_t* returnWideStringArrayElement(wchar_t* args[], int which) {
return args[which];
}
对应的JAVA映射如下:
String returnStringArrayElement(String[] args, int which);
WString returnWideStringArrayElement(WString[] args, int which);
int fillInt8Buffer(ByteBuffer buf, int len, byte value);
然后看下具体怎么使用:
TestLibrary lib = Native.load("testlib", TestLibrary.class);
ByteBuffer buf = ByteBuffer.allocate(1024).order(ByteOrder.nativeOrder());
final byte MAGIC = (byte)0xED;
lib.fillInt8Buffer(buf, 1024, MAGIC);
for (int i=0;i < buf.capacity();i++) {
assertEquals("Bad value at index " + i, MAGIC, buf.get(i));
}
可变参数
对于native和JAVA本身来说,都是支持可变参数的,我们举个例子,在native方法中:
int32_t addVarArgs(const char *fmt, ...) {
va_list ap;
int32_t sum = 0;
va_start(ap, fmt);
while (*fmt) {
switch (*fmt++) {
case 'd':
sum += va_arg(ap, int32_t);
break;
case 'l':
sum += (int) va_arg(ap, int64_t);
break;
case 's': // short (promoted to 'int' when passed through '...')
case 'c': // byte/char (promoted to 'int' when passed through '...')
sum += (int) va_arg(ap, int);
break;
case 'f': // float (promoted to ‘double’ when passed through ‘...’)
case 'g': // double
sum += (int) va_arg(ap, double);
break;
default:
break;
}
}
va_end(ap);
return sum;
}
对应的JAVA方法映射如下:
public int addVarArgs(String fmt, Number... args);
相应的调用代码如下:
int arg1 = 1;
int arg2 = 2;
assertEquals("32-bit integer varargs not added correctly", arg1 + arg2,
lib.addVarArgs("dd", arg1, arg2));