by stevefan1999 · 2y ago · 0 comments
In C# I can just do something like this conceptual code:
```
// FILE *fopen(const char *filename, const char *mode)
[DllImport("libc")] public unsafe extern nint fopen([MarshalAs(UnmanagedType.LPStr)] string filename, [MarshalAs(UnmanagedType.LPStr)] string mode);
// char *fgets(char *str, int n, FILE *stream)
[DllImport("libc")] public unsafe extern nint fgets([MarshalAs(UnmanagedType.LPStr)] string str, int n, nint stream);
// int fclose(FILE *stream)
[DllImport("libc")] public unsafe extern int fclose(nint stream);
```
So much less code, and so much more precise than any of the Java JNI and FFI stuff.
I'm sure someone will come along and write annotations to do exactly as you describe there. The Java language folks tend to be very conservative about putting stuff in the official API, cuz they know it'll have to stay there for 30+ years. They prefer to let the community write something like annotations over low-level APIs.
Anyway, the GraalVM folks don't have quite the same limitations as Java, so they have annotations already (https://yyhh.org/blog/2021/02/writing-c-code-in-javaclojure-...):
@CStruct("MDB_val")
public interface MDB_val extends PointerBase {
@CField("mv_size")
long get_mv_size();
@CField("mv_size")
void set_mv_size(long value);
@CField("mv_data")
VoidPointer get_mv_data();
@CField("mv_data")
void set_mv_data(VoidPointer value);
} var text = "Hello, World!"u8;
write(1, text, text.Length);
[DllImport("libc")]
static extern nint write(nint fd, ReadOnlySpan<byte> buf, nint count);
(note: it's recommended to use [LibraryImport] instead for p/invoke declarations that require marshalling as it does not require JIT/runtime marshalling but just generates (better) p/invoke stub at build time)