using System.Runtime.InteropServices.Marshalling; namespace Brutal.SlangApi; /// /// The Slang class provides access to the slang library for compiling shaders. /// /// /// Release returned COM proxies with on the thread using /// them, in reverse dependency order: code/diagnostics and components, modules, /// session, then global session. Keep parents alive until their children have /// been released. The garbage collector never releases a proxy, so one that is /// not passed to keeps its native object alive. /// Each returned proxy owns an independent reference; releasing one proxy does /// not invalidate another proxy for the same native object. /// public static partial class Slang { /// /// instance used to bridge raw COM pointers obtained from /// slang_* entry points (e.g. ) /// into managed [GeneratedComInterface] proxies. /// keeps ' discovery of the proxy classes /// emitted by the source generator from the type's IID, so no per-interface /// registration is needed. /// internal static readonly StrategyBasedComWrappers ComWrappers = new SlangComWrappers(); public static partial class PInvoke { static PInvoke() { var assembly = typeof(Slang).Assembly; var nativeDll = NativeLibrary.Load("slang", assembly, DllImportSearchPath.AssemblyDirectory); // Slang loads slang-glslang and slang-glsl-module by bare name at run time. Windows // searches only the application and system directories for them, which misses a // RID-less NuGet build's runtimes/win-x64/native folder, so load them from wherever // slang came from; Slang's own LoadLibrary then finds the loaded modules. macOS and // Linux resolve them through slang's rpath. if (OperatingSystem.IsWindows()) foreach (var companion in (ReadOnlySpan)["slang-glslang", "slang-glsl-module"]) NativeLibrary.TryLoad(companion, assembly, DllImportSearchPath.AssemblyDirectory, out _); NativeLibrary.SetDllImportResolver( assembly, (libraryName, _, _) => libraryName == "slang" ? nativeDll : IntPtr.Zero ); } } /// /// Throwing form of : /// returns a managed COM proxy on success, throws /// on failure or if the native call succeeds but yields /// a null session pointer. /// public static IGlobalSession CreateGlobalSession(Int apiVersion = Constants.ApiVersion) => Unwrap(TryCreateGlobalSession(apiVersion, out var session), session); /// /// Result-returning form: invokes slang_createGlobalSession and wraps the raw /// IUnknown pointer it produces into a managed . The /// out-parameter is null when the call fails or the /// native side returns a null pointer. /// public static Result TryCreateGlobalSession(Int apiVersion, out IGlobalSession? session) { var hr = PInvoke.slang_createGlobalSession(apiVersion, out var raw); session = WrapComInstance(hr, raw); return hr; } public static IGlobalSession CreateGlobalSession(in GlobalSessionDesc desc) => Unwrap(TryCreateGlobalSession(in desc, out var session), session); public static Result TryCreateGlobalSession(in GlobalSessionDesc desc, out IGlobalSession? session) { var hr = PInvoke.slang_createGlobalSession2(in desc, out var raw); session = WrapComInstance(hr, raw); return hr; } public static IGlobalSession CreateGlobalSessionWithoutCoreModule(Int apiVersion = Constants.ApiVersion) => Unwrap(TryCreateGlobalSessionWithoutCoreModule(apiVersion, out var session), session); public static Result TryCreateGlobalSessionWithoutCoreModule(Int apiVersion, out IGlobalSession? session) { var hr = PInvoke.slang_createGlobalSessionWithoutCoreModule(apiVersion, out var raw); session = WrapComInstance(hr, raw); return hr; } /// /// Creates an over a copy of . Slang /// allocates and owns the blob's storage, so the input span doesn't need to outlive /// the call. Throws if slang returns a null pointer (typically an out-of-memory /// condition). /// public static unsafe ISlangBlob CreateBlob(ReadOnlySpan data) { nint raw; fixed (byte* p = data) raw = PInvoke.slang_createBlob(p, Brutal.ByteSize.Of(data)); if (raw == 0) throw new SlangException((Result)(-1), "slang_createBlob returned a null pointer."); return WrapComInstance((Result)0, raw)!; } /// /// Throwing form of . /// Returns the textual-disassembly blob produced by slang from /// . Throws on failure or if slang reports success with /// a null pointer. /// public static ISlangBlob DisassembleByteCode(ISlangBlob moduleBlob) => Unwrap(TryDisassembleByteCode(moduleBlob, out var disassembly), disassembly); /// /// Result-returning form: converts to a raw COM pointer /// for the duration of the flat-C slang_disassembleByteCode call (releasing /// the extra reference afterwards) and wraps the returned pointer back into a managed /// . The out-parameter is null /// when the call fails or slang returns a null pointer. /// public static Result TryDisassembleByteCode(ISlangBlob moduleBlob, out ISlangBlob? disassembly) { var rawIn = GetComInstance(moduleBlob); try { var hr = PInvoke.slang_disassembleByteCode(rawIn, out var rawOut); disassembly = WrapComInstance(hr, rawOut); return hr; } finally { Marshal.Release(rawIn); } } /// /// Throws if the result is a failure, or if a successful result was paired with a /// null COM proxy (which indicates the native side handed back a null pointer /// despite reporting success). /// private static T Unwrap(Result hr, T? session) where T : class { hr.ThrowIfFailure(); return session ?? throw new SlangException(hr, $"slang returned a success Result with a null {typeof(T).Name}."); } /// /// Wraps a raw COM IUnknown pointer into a managed proxy of the requested /// interface type. Returns null when the underlying call failed or the /// native side handed back a null pointer. /// internal static T? WrapComInstance(Result hr, nint comInstance) where T : class { if (comInstance == 0) return null; try { return hr.IsFailure ? null : WrapBorrowedComInstance(comInstance); } finally { // The RCW retains its own reference. Consume the reference transferred by // the native export, including when interface conversion throws. Marshal.Release(comInstance); } } internal static T? WrapBorrowedComInstance(nint pointer) where T : class { if (pointer == 0) return null; var wrapper = ComWrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.UniqueInstance); // Only Release frees a proxy's native references. Its finalizer would release them // on the finalizer thread, in no order relative to the proxy's session. GC.SuppressFinalize(wrapper); try { return (T)wrapper; } catch { ((ComObject)wrapper).FinalRelease(); throw; } } /// /// Releases a proxy returned by this binding immediately. This is the only way a /// proxy's native reference is released: the garbage collector never does it. /// Null and repeated releases are harmless. Do not use the proxy afterwards. Release children /// before their owning session and release sessions before their global session. /// Do not race release against another call using the same proxy. /// public static void Release(object? instance) { if (instance is null) return; if (instance is not ComObject wrapper) throw new ArgumentException("Expected a Slang COM proxy.", nameof(instance)); wrapper.FinalRelease(); } /// /// Returns the underlying COM IUnknown pointer for a managed proxy. Used by /// callers passing managed COM objects into deprecated sp* PInvokes which /// take raw nint pointers. The returned pointer carries an extra reference /// count. Call on it when finished, or pass it to /// APIs that take ownership. /// public static nint GetComInstance(object comObject) { ArgumentNullException.ThrowIfNull(comObject); if (comObject is ComObject) return GetComInstance((ISlangUnknown)comObject); return System.Runtime.InteropServices.ComWrappers.TryGetComInstance(comObject, out var native) ? native : ComWrappers.GetOrCreateComInterfaceForObject(comObject, CreateComInterfaceFlags.None); } /// /// Gets an owned pointer to the requested native interface, including its correct /// subobject address. Release the returned reference after the native call. /// public static unsafe nint GetComInstance(T comObject) where T : class { if (comObject is ComObject wrapper) { var table = ((IUnmanagedVirtualMethodTableProvider)wrapper).GetVirtualMethodTableInfoForKey(typeof(T)); var pointer = (nint)table.ThisPointer; Marshal.AddRef(pointer); GC.KeepAlive(wrapper); return pointer; } return (nint)ComInterfaceMarshaller.ConvertToUnmanaged(comObject); } }