Skip to content

Instantly share code, notes, and snippets.

Last active May 21, 2021 08:16
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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
$GRAALVM_HOME/bin/native-image --no-server --no-fallback SetEnv
$ ./setenv foo 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 org.graalvm.nativeimage.c.type.CTypeConversion;
import org.graalvm.nativeimage.c.type.CTypeConversion.CCharPointerHolder;
import java.util.List;
import java.util.Collections;
public class SetEnv {
static class MyDirectives implements CContext.Directives {
public List<String> getHeaderFiles() {
return Collections.singletonList("<stdlib.h>");
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]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment