UNIXworkcode

1 /* 2 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 3 * Version 2, December 2004 4 * 5 * Copyright (C) 2018 Olaf Wintermann <olaf.wintermann@gmail.com> 6 * 7 * Everyone is permitted to copy and distribute verbatim or modified 8 * copies of this license document, and changing it is allowed as long 9 * as the name is changed. 10 * 11 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 12 * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 13 * 14 * 0. You just DO WHAT THE FUCK YOU WANT TO. 15 */ 16 17 // GraalVM example: mixing Java and native Code (LLVM bitcode) 18 19 import org.graalvm.polyglot.*; 20 import java.io.*; 21 22 /* 23 * create a file test.c with the following content and compile it with: 24 * clang -c -O1 -emit-llvm test.c 25 26 #include <stdio.h> 27 28 int main(void) { 29 printf("Hello World!\n"); 30 return 0; 31 } 32 33 int add(int a, int b) { 34 return a+b; 35 } 36 37 */ 38 39 public class HelloPolyglot { 40 public static void main(String[] args) { 41 try { 42 // create a polyglot context that can access the native interface 43 Context ctx = Context.newBuilder().allowAllAccess(true).build(); 44 45 // load an llvm bitcode file 46 File file = new File("test.bc"); 47 Source source = Source.newBuilder("llvm", file).build(); 48 Value c = ctx.eval(source); 49 50 // get the main function and execute it 51 c.getMember("main").execute(); 52 53 // get add function 54 Value add = c.getMember("add"); 55 Value ret = add.execute(10, 20); 56 System.out.println(ret.asInt()); 57 } catch (IOException e) { 58 System.err.println(e); 59 } 60 } 61 } 62