Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Last active March 25, 2018 16:35
Show Gist options
  • Save bitsnaps/136511745bf3db0866440b84b3ad2b7a to your computer and use it in GitHub Desktop.
Save bitsnaps/136511745bf3db0866440b84b3ad2b7a to your computer and use it in GitHub Desktop.
Groovy and JNA simple example (C & C++ on Win64bit)
@echo off
echo Compiling C/C++
REM C library
gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o helloc.dll hello.c
REM C++ library
g++ -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o hellocpp.dll hello.cpp
echo Running groovy script
groovy -cp hello.dll hello.groovy
REM if you have jna.jar include it to the classpath:
REM groovy -cp "jna.jar;hello.dll" hello.groovy
#include <stdio.h>
void printValue(char* value) {
printf("\n%s\n\n", value);
}
#include <iostream>
using namespace std;
extern "C" void printValue(char* value){
cout << value << endl;
}
// https://mvnrepository.com/artifact/net.java.dev.jna/jna
@Grab(group='net.java.dev.jna', module='jna', version='4.1.0')
import com.sun.jna.Native
import com.sun.jna.Library
// Define an Interface that exactly matches our header file
interface Hello extends Library {
void printValue(String value)
}
try {
// Load library into an instance of NativeInterface
def nativeLibraryC = Native.loadLibrary('helloC', Hello.class)
def nativeLibraryCpp = Native.loadLibrary('helloCpp', Hello.class)
// Call method - JNA intercepts this and invokes the library for us
nativeLibraryC.printValue('Groovy JNA execute C library')
nativeLibraryCpp.printValue('Groovy JNA execute C++ library')
} catch( UnsatisfiedLinkError e ) {
println 'Failed to load library'
e.printStackTrace()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment