Last active
May 21, 2021 08:16
-
-
Save borkdude/335c9911cabf4db6d47cc772b4c69d4d to your computer and use it in GitHub Desktop.
C's setenv called from Java in a native image
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
#!/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 |
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
$ ./setenv foo bar | |
bar |
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
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