Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/main/java/jnr/ffi/annotations/NativeName.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package jnr.ffi.annotations;

import java.lang.annotation.*;

/**
* Use if you want to have different names for JNR interface method and native library method.
* <b/>
* For mapping to work, use {@link jnr.ffi.mapper.NativeNameFunctionMapper}
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NativeName {
String value();
}
28 changes: 28 additions & 0 deletions src/main/java/jnr/ffi/mapper/NativeNameFunctionMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package jnr.ffi.mapper;

import jnr.ffi.annotations.NativeName;

import java.lang.annotation.Annotation;
import java.util.Collection;

/**
* Uses {@link NativeName} annotation to map JNR interface method and native library method with different names.
* Example:
* <pre>
* {@code
* LibC libc = LibraryLoader.create(LibC.class).mapper(new NativeNameFunctionMapper()).load("lib");
* }
* </pre>
*/
public class NativeNameFunctionMapper implements FunctionMapper {
@Override
public String mapFunctionName(String functionName, Context context) {
Collection<Annotation> annotations = context.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof NativeName) {
return ((NativeName) annotation).value();
}
}
return functionName;
}
}
42 changes: 42 additions & 0 deletions src/test/java/jnr/ffi/mapper/NativeNameFunctionMapperTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package jnr.ffi.mapper;

import jnr.ffi.LibraryLoader;
import jnr.ffi.annotations.NativeName;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Random;

/**
* Created by Andrew
* on 01.07.2017.
*/
public class NativeNameFunctionMapperTest {
static Lib lib;

@BeforeClass
public static void setUpClass()
throws Exception {
lib = LibraryLoader.create(Lib.class)
.mapper(new NativeNameFunctionMapper())
.load("test");
}

@Test
public void testSameFunctionResult()
throws Exception {
Random random = new Random();
for (int i = 0; i < 100; i++) {
int randomInt = random.nextInt();
Assert.assertEquals(lib.ret_int32_t(randomInt), lib.returnInt(randomInt));
}
}

public static interface Lib {
public int ret_int32_t(int value);

@NativeName("ret_int32_t")
public int returnInt(int value);
}
}