Last active
March 25, 2018 16:35
-
-
Save bitsnaps/136511745bf3db0866440b84b3ad2b7a to your computer and use it in GitHub Desktop.
Groovy and JNA simple example (C & C++ on Win64bit)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void printValue(char* value) { | |
printf("\n%s\n\n", value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
extern "C" void printValue(char* value){ | |
cout << value << endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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