Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GraalVM shared library example which receives String arguments called from C
$ javac org/komamitsu/foobar/SharedStringMethod.java
$ native-image --shared -H:Name=libfoobar
$ cc -Wall '-Wl,-rpath,$ORIGIN' -I. -L. -lfoobar main.c
$ ./a.out
result: hello world
#include <stdio.h>
#include <stdlib.h>
#include <libfoobar.h>
int main(void) {
int ret;
graal_isolatethread_t *isolate_thread = NULL;
ret = graal_create_isolate(NULL, NULL, &isolate_thread);
if (ret != 0) {
fprintf(stderr, "graal_create_isolate: %d\n", ret);
return 1;
}
char *result = NULL;
result = add(isolate_thread, "hello ", "world");
if (result == NULL) {
fprintf(stderr, "add() returned NULL\n");
return 1;
}
printf("result: %s\n", result);
ret = graal_tear_down_isolate(isolate_thread);
if (ret != 0) {
fprintf(stderr, "graal_tear_down_isolate: %d\n", ret);
return 1;
}
return 0;
}
package org.komamitsu.foobar;
import org.graalvm.nativeimage.IsolateThread;
import org.graalvm.nativeimage.c.function.CEntryPoint;
import org.graalvm.nativeimage.c.type.CCharPointer;
import org.graalvm.nativeimage.c.type.CTypeConversion;
public class SharedStringMethod
{
@CEntryPoint(name = "add")
public static CCharPointer add(
IsolateThread isolateThread,
CCharPointer rawA,
CCharPointer rawB
) {
String a = CTypeConversion.toJavaString(rawA);
String b = CTypeConversion.toJavaString(rawB);
try (CTypeConversion.CCharPointerHolder pointerHolder = CTypeConversion.toCString(a + b)) {
return pointerHolder.get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment