diff --git a/src/main/java/jnr/ffi/annotations/NativeName.java b/src/main/java/jnr/ffi/annotations/NativeName.java new file mode 100644 index 000000000..e0ee7087b --- /dev/null +++ b/src/main/java/jnr/ffi/annotations/NativeName.java @@ -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. + * + * For mapping to work, use {@link jnr.ffi.mapper.NativeNameFunctionMapper} + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface NativeName { + String value(); +} diff --git a/src/main/java/jnr/ffi/mapper/NativeNameFunctionMapper.java b/src/main/java/jnr/ffi/mapper/NativeNameFunctionMapper.java new file mode 100644 index 000000000..3cc24e5c8 --- /dev/null +++ b/src/main/java/jnr/ffi/mapper/NativeNameFunctionMapper.java @@ -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: + *
+ * {@code
+ * LibC libc = LibraryLoader.create(LibC.class).mapper(new NativeNameFunctionMapper()).load("lib");
+ * }
+ * 
+ */ +public class NativeNameFunctionMapper implements FunctionMapper { + @Override + public String mapFunctionName(String functionName, Context context) { + Collection annotations = context.getAnnotations(); + for (Annotation annotation : annotations) { + if (annotation instanceof NativeName) { + return ((NativeName) annotation).value(); + } + } + return functionName; + } +} diff --git a/src/test/java/jnr/ffi/mapper/NativeNameFunctionMapperTest.java b/src/test/java/jnr/ffi/mapper/NativeNameFunctionMapperTest.java new file mode 100644 index 000000000..1514df484 --- /dev/null +++ b/src/test/java/jnr/ffi/mapper/NativeNameFunctionMapperTest.java @@ -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); + } +}