1using System.Runtime.CompilerServices;
2using System.Runtime.InteropServices;
7public static partial class FileEmitter
10 private enum FileFlags
18 [LibraryImport(
"c", EntryPoint =
"open", SetLastError =
true, StringMarshalling = StringMarshalling.Utf8)]
19 [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
20 private static unsafe partial
int Open([MarshalAs(UnmanagedType.LPUTF8Str)]
string path, FileFlags flags);
22 [LibraryImport(
"c", EntryPoint =
"write", SetLastError =
true)]
23 [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
24 private static unsafe partial
int Write(
int fd,
void* buffer, nuint size);
26 [LibraryImport(
"c", EntryPoint =
"close", SetLastError =
true)]
27 [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
28 private static unsafe partial
int Close(
int fd);
30 [LibraryImport(
"kernel32", EntryPoint =
"WriteFileA", SetLastError =
true)]
31 private static unsafe partial
int WriteFile(
36 NativeOverlapped* lpOverlapped);
40 EntryPoint =
"CreateFileW",
42 StringMarshalling = StringMarshalling.Utf16)]
43 private static partial IntPtr CreateFileW(
44 [MarshalAs(UnmanagedType.LPWStr)]
string filename,
47 IntPtr securityAttributes,
48 FileMode creationDisposition,
49 FileAttributes flagsAndAttributes,
52 [LibraryImport(
"kernel32", EntryPoint =
"CloseHandleA", SetLastError =
true)]
53 [
return: MarshalAs(UnmanagedType.Bool)]
54 private static unsafe partial
bool CloseHandle(IntPtr handle);
56 [LibraryImport(
"c", EntryPoint =
"getcwd", SetLastError =
true)]
57 private static unsafe partial
byte* GetCurrentDirectory(
byte* buf, nuint size);
59 [LibraryImport(
"kernel32", EntryPoint =
"GetCurrentDirectoryW", SetLastError =
true)]
60 private static unsafe partial uint GetCurrentDirectory(uint nBufferLength,
byte* lpBuffer);
62 public static string GetCurrentDirectory()
64 var buffer =
new byte[65535];
67 fixed (
byte* p = buffer)
69 if (OperatingSystem.IsWindows())
70 GetCurrentDirectory((uint)buffer.Length, p);
72 GetCurrentDirectory(p, (nuint)buffer.Length);
74 return Marshal.PtrToStringUTF8((IntPtr)p, buffer.Length);
79 public static void Write(
string path,
string text)
81 var windows = OperatingSystem.IsWindows();
89 FileMode.OpenOrCreate,
92 : Open(path, FileFlags.WriteOnly | FileFlags.Create);
94 Console.WriteLine($
"Failed to open file: {Marshal.GetLastWin32Error()}");
98 var buffer = Encoding.UTF8.GetBytes(text);
99 var len = buffer.Length;
100 fixed (byte* p = buffer)
103 WriteFile((void*)handle, p, len, &len, null);
105 Write((int)handle, p, (UIntPtr)len);