Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Last active July 13, 2016 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitsnaps/44ac4fc963044041ba07ca07a6324280 to your computer and use it in GitHub Desktop.
Save bitsnaps/44ac4fc963044041ba07ca07a6324280 to your computer and use it in GitHub Desktop.
Groovy JNAerator example using JNA and BridJ
@echo off
REM Compile script on Windows machine
echo Compiling C
gcc -c -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" hello.c
echo Generating o library
gcc -Wl,--add-stdcall-alias -shared -o hello.dll hello.o
echo Generate header interface using JNAcreator
java -jar jnaerator.jar -mode Jar -jar hello.jar -runtime JNA -library hello hello.h
rem java -jar jnaerator.jar -mode Jar -jar hello.jar -runtime BridJ -library hello hello.h
echo Running groovy script
groovy -cp "jnaerator.jar;hello.jar" hello.groovy
rem (I got jnaerator.jar after compiling: "https://github.com/nativelibs4java/JNAerator" look for jnaerator-*shraded.jar) or get it from here:
rem http://www.4shared.com/file/NArd2rh2ce/jnaerator.html
rem clean folder
rem del *.o; del hello.dll; del hello.jar
pause
#include <stdio.h>
void printValue(char* value) {
for (int i = 0; i< 5; i++){
printf("i=%d\n", i);
}
printf("\n%s\n\n", value);
}
import java.nio.ByteBuffer
import com.sun.jna.Native
import java.nio.charset.Charset
import org.bridj.Pointer
import org.bridj.Pointer.StringType
import hello.HelloLibrary
def framework = HelloLibrary.class.isAnnotationPresent(org.bridj.ann.Library)? 'BridJ': 'JNA'
def value = "Go go gadget ${framework}"
try {
if (framework == 'JNA'){
// Build a ByteBuffer - roughly analagous to a Pointer to memory block
value = ByteBuffer.wrap(Native.toByteArray(value))
// Tell JNA to build an interface to the Native Library
def library = Native.loadLibrary(HelloLibrary.class)
// Pass the ByteBuffer to the Native Library function
library.printValue(value)
} else { // BridJ
// Build a pointer to your String (turn it into a more C-like String)
value = Pointer.pointerToString("Go go gadget BridJ", StringType.C, Charset.defaultCharset())
// Invoke native library method (with BridJ doing the heavy lifting)
HelloLibrary.printValue(value)
}
} catch( UnsatisfiedLinkError e ) {
println 'Failed to load library'
e.printStackTrace()
}
#ifndef nativegroovy_h__
#define nativegroovy_h__
extern void printValue(char* value);
#endif //nativegroovy_h__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment