Skip to content

Instantly share code, notes, and snippets.

@borkdude
Last active May 21, 2021 08:16
Show Gist options
  • Save borkdude/335c9911cabf4db6d47cc772b4c69d4d to your computer and use it in GitHub Desktop.
Save borkdude/335c9911cabf4db6d47cc772b4c69d4d to your computer and use it in GitHub Desktop.
C's setenv called from Java in a native image
#!/usr/bin/env bash
set -eou pipefail
SVM_JAR=$(find -L "$GRAALVM_HOME" | grep svm.jar)
$GRAALVM_HOME/bin/javac -cp $SVM_JAR SetEnv.java
$GRAALVM_HOME/bin/native-image --no-server --no-fallback SetEnv
$ ./setenv foo bar
bar
import org.graalvm.nativeimage.c.function.CFunction;
import org.graalvm.nativeimage.c.function.CFunction.Transition;
import org.graalvm.nativeimage.c.function.CLibrary;
import org.graalvm.nativeimage.c.CContext;
import org.graalvm.nativeimage.c.type.CCharPointer;
import com.oracle.svm.core.c.ProjectHeaderFile;
import org.graalvm.nativeimage.c.type.CTypeConversion;
import org.graalvm.nativeimage.c.type.CTypeConversion.CCharPointerHolder;
import java.util.List;
import java.util.Collections;
@CContext(SetEnv.MyDirectives.class)
public class SetEnv {
static class MyDirectives implements CContext.Directives {
@Override
public List<String> getHeaderFiles() {
return Collections.singletonList("<stdlib.h>");
}
}
@CFunction
private static native int setenv(CCharPointer name, CCharPointer value, int overwrite);
// API
public static void setEnv(String name, String value) {
try (CCharPointerHolder nameHolder = CTypeConversion.toCString(name);
CCharPointerHolder valueHolder = CTypeConversion.toCString(value)) {
setenv(nameHolder.get(), valueHolder.get(), 1);
}
}
public static void main(String[] args) {
setEnv(args[0], args[1]);
System.out.println(System.getenv(args[0]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment