using System.Runtime.InteropServices.Marshalling;
namespace Brutal.SlangApi;
///
/// The Slang class provides access to the slang library for compiling shaders.
///
///
/// Slang COM proxies (returned by ,
/// , etc.) are released by the ComWrappers
/// finalizer when GC reclaims the managed proxy. There is no deterministic
/// Dispose. Callers don't need to do anything special. COM proxies in this
/// binding represent shared-ownership references; the underlying slang object stays
/// alive as long as anything (slang internals, other proxies, or the global session)
/// holds a reference, regardless of when any single proxy is collected.
///
public static partial class Slang
{
///
/// instance used to bridge raw COM pointers obtained from
/// slang_* entry points (e.g. )
/// into managed [GeneratedComInterface] proxies. The default
/// implementation discovers 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();
public static partial class PInvoke
{
static PInvoke()
{
var assembly = typeof(Slang).Assembly;
var nativeDll = NativeLibrary.Load("slang", assembly, DllImportSearchPath.AssemblyDirectory);
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.ByteSize64)data.Length);
if (raw == 0)
throw new SlangException((Result)(-1), "slang_createBlob returned a null pointer.");
return (ISlangBlob)ComWrappers.GetOrCreateObjectForComInstance(raw, CreateObjectFlags.None);
}
///
/// 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 (hr.IsFailure || comInstance == 0)
return null;
return (T)ComWrappers.GetOrCreateObjectForComInstance(comInstance, CreateObjectFlags.None);
}
///
/// 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) =>
ComWrappers.GetOrCreateComInterfaceForObject(comObject, CreateComInterfaceFlags.None);
}