mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
6 changed files with 768360 additions and 0 deletions
|
|
@ -0,0 +1,58 @@
|
|||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace Brutal.Interop.SourceGenerators;
|
||||
|
||||
[Generator]
|
||||
public class InteropHandleGenerator : IIncrementalGenerator
|
||||
{
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var pipeline = context.SyntaxProvider.ForAttributeWithMetadataName(
|
||||
fullyQualifiedMetadataName: "Brutal.Interop.InteropHandleAttribute",
|
||||
predicate: static (node, _) => node is StructDeclarationSyntax,
|
||||
transform: static (ctx, _) => new Model(ctx)
|
||||
);
|
||||
|
||||
context.RegisterSourceOutput(pipeline, static (ctx, model) => model.Generate(ctx));
|
||||
}
|
||||
|
||||
private readonly record struct Model
|
||||
{
|
||||
private readonly string? _namespace;
|
||||
private readonly string _typeName;
|
||||
|
||||
public Model(GeneratorAttributeSyntaxContext context)
|
||||
{
|
||||
var symbol = (INamedTypeSymbol)context.TargetSymbol;
|
||||
_namespace = symbol.ContainingNamespace is { IsGlobalNamespace: false } ns
|
||||
? ns.ToDisplayString()
|
||||
: null;
|
||||
_typeName = symbol.Name;
|
||||
}
|
||||
|
||||
public void Generate(SourceProductionContext context)
|
||||
{
|
||||
var nsDecl = _namespace is not null ? $"namespace {_namespace};\n\n" : "";
|
||||
|
||||
var source = $$"""
|
||||
#nullable enable
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
using Brutal.Interop;
|
||||
|
||||
{{nsDecl}}[NativeMarshalling(typeof(InteropHandleMarshaller<{{_typeName}}, {{_typeName}}.Handle>))]
|
||||
public readonly unsafe partial struct {{_typeName}} : IInteropHandle<{{_typeName}}.Handle, {{_typeName}}>
|
||||
{
|
||||
public record struct Handle(nint Value);
|
||||
public required Handle Pointer { get; init; }
|
||||
public bool IsNull() => Pointer.Value == 0;
|
||||
public static implicit operator {{_typeName}}(void* ptr) => new() { Pointer = new Handle((nint)ptr) };
|
||||
}
|
||||
""";
|
||||
|
||||
context.AddSource($"{_typeName}.g.cs", SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
}
|
||||
11
brutal.interop/Brutal.Interop/IInteropHandle.cs
Normal file
11
brutal.interop/Brutal.Interop/IInteropHandle.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
namespace Brutal.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// Describes an object that can be marshalled between managed and unmanaged code via a typed handle.
|
||||
/// </summary>
|
||||
public interface IInteropHandle<THandle, out TSelf> : INullable
|
||||
where THandle : unmanaged
|
||||
where TSelf : struct, IInteropHandle<THandle, TSelf>
|
||||
{
|
||||
THandle Pointer { get; init; }
|
||||
}
|
||||
6
brutal.interop/Brutal.Interop/InteropHandleAttribute.cs
Normal file
6
brutal.interop/Brutal.Interop/InteropHandleAttribute.cs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
using System;
|
||||
|
||||
namespace Brutal.Interop;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Struct)]
|
||||
public sealed class InteropHandleAttribute : Attribute { }
|
||||
18
brutal.interop/Brutal.Interop/InteropHandleMarshaller.cs
Normal file
18
brutal.interop/Brutal.Interop/InteropHandleMarshaller.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
|
||||
namespace Brutal.Interop;
|
||||
|
||||
[CustomMarshaller(
|
||||
typeof(CustomMarshallerAttribute.GenericPlaceholder),
|
||||
MarshalMode.Default,
|
||||
typeof(InteropHandleMarshaller<,>)
|
||||
)]
|
||||
public static class InteropHandleMarshaller<T, THandle>
|
||||
where THandle : unmanaged
|
||||
where T : struct, IInteropHandle<THandle, T>
|
||||
{
|
||||
public static THandle ConvertToUnmanaged(T managed) => managed.Pointer;
|
||||
|
||||
public static T ConvertToManaged(THandle unmanaged) => Unsafe.As<THandle, T>(ref unmanaged);
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
|
||||
namespace Brutal.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// Marshaller for UTF-8 strings whose out direction preserves a NULL native
|
||||
/// pointer as <see langword="null"/>. The null-preserving sibling of
|
||||
/// <see cref="InteropStringMarshaller"/>, for native APIs that use a NULL
|
||||
/// return as a failure or absence sentinel.
|
||||
/// </summary>
|
||||
[CustomMarshaller(
|
||||
typeof(string),
|
||||
MarshalMode.ManagedToUnmanagedIn,
|
||||
typeof(InteropStringMarshaller.ManagedToUnmanagedIn)
|
||||
)] // string parameter, shared with the non-nullable sibling
|
||||
[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedOut, typeof(ManagedToUnmanagedOut))] // return string?
|
||||
public static unsafe class InteropNullableStringMarshaller
|
||||
{
|
||||
public static class ManagedToUnmanagedOut
|
||||
{
|
||||
public static string? ConvertToManaged(byte* unmanaged)
|
||||
{
|
||||
if (unmanaged == null)
|
||||
return null;
|
||||
|
||||
return Marshal.PtrToStringUTF8((IntPtr)unmanaged);
|
||||
}
|
||||
}
|
||||
}
|
||||
178
brutal.interop/Brutal.Interop/InteropStringMarshaller.cs
Normal file
178
brutal.interop/Brutal.Interop/InteropStringMarshaller.cs
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
using System.Text;
|
||||
|
||||
namespace Brutal.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// Marshaller for UTF-8 strings.
|
||||
/// </summary>
|
||||
[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedIn, typeof(ManagedToUnmanagedIn))] // string parameter
|
||||
[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedOut, typeof(ManagedToUnmanagedOut))] // return string
|
||||
//[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedRef, typeof(ManagedToUnmanagedRef))]
|
||||
//[CustomMarshaller(typeof(string), MarshalMode.UnmanagedToManagedIn, typeof(UnmanagedToManagedIn))]
|
||||
//[CustomMarshaller(typeof(string), MarshalMode.UnmanagedToManagedRef, typeof(UnmanagedToManagedRef))]
|
||||
//[CustomMarshaller(typeof(string), MarshalMode.UnmanagedToManagedOut, typeof(UnmanagedToManagedOut))]
|
||||
//[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedIn, typeof(ManagedToUnmanagedIn))]
|
||||
public static unsafe class InteropStringMarshaller
|
||||
{
|
||||
/// <summary>
|
||||
/// Custom marshaller to marshal a managed string as a UTF-8 unmanaged string.
|
||||
/// </summary>
|
||||
public ref struct ManagedToUnmanagedIn
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the requested buffer size for optimized marshalling.
|
||||
/// </summary>
|
||||
public static int BufferSize => 0x100;
|
||||
|
||||
private byte* _unmanagedValue;
|
||||
private bool _allocated;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the marshaller with a managed string and requested buffer.
|
||||
/// </summary>
|
||||
/// <param name="managed">The managed string with which to initialize the marshaller.</param>
|
||||
/// <param name="buffer">The request buffer whose size is at least <see cref="BufferSize"/>.</param>
|
||||
public void FromManaged(string? managed, Span<byte> buffer)
|
||||
{
|
||||
_allocated = false;
|
||||
|
||||
if (managed is null)
|
||||
{
|
||||
_unmanagedValue = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const int MaxUtf8BytesPerChar = 3;
|
||||
|
||||
// >= for null terminator
|
||||
// Use the cast to long to avoid the checked operation
|
||||
if ((long)MaxUtf8BytesPerChar * managed.Length >= buffer.Length)
|
||||
{
|
||||
// Calculate accurate byte count when the provided stack-allocated buffer is not sufficient
|
||||
int exactByteCount = checked(Encoding.UTF8.GetByteCount(managed) + 1); // + 1 for null terminator
|
||||
if (exactByteCount > buffer.Length)
|
||||
{
|
||||
buffer = new Span<byte>(
|
||||
(byte*)NativeMemory.Alloc((nuint)exactByteCount),
|
||||
exactByteCount
|
||||
);
|
||||
_allocated = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Unsafe.AsPointer is safe since buffer must be pinned
|
||||
_unmanagedValue = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer));
|
||||
|
||||
int byteCount = Encoding.UTF8.GetBytes(managed, buffer);
|
||||
buffer[byteCount] = 0; // null-terminate
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the current managed string to an unmanaged string.
|
||||
/// </summary>
|
||||
/// <returns>An unmanaged string.</returns>
|
||||
public byte* ToUnmanaged() => _unmanagedValue;
|
||||
|
||||
/// <summary>
|
||||
/// Frees any allocated unmanaged memory.
|
||||
/// </summary>
|
||||
public void Free()
|
||||
{
|
||||
if (_allocated)
|
||||
NativeMemory.Free(_unmanagedValue);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ManagedToUnmanagedOut
|
||||
{
|
||||
public static string ConvertToManaged(byte* unmanaged)
|
||||
{
|
||||
if (unmanaged == null)
|
||||
return string.Empty;
|
||||
|
||||
var result = Marshal.PtrToStringUTF8((IntPtr)unmanaged);
|
||||
|
||||
if (result is null)
|
||||
return string.Empty;
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
public ref struct ManagedToUnmanagedRef
|
||||
{
|
||||
public void FromManaged(string managed) { }
|
||||
|
||||
public void FromUnmanaged(byte* unmanaged)
|
||||
{
|
||||
}
|
||||
|
||||
public string ToManaged()
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public byte* ToUnmanaged()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Free() { }
|
||||
}
|
||||
|
||||
|
||||
public ref struct UnmanagedToManagedOut
|
||||
{
|
||||
public void FromManaged(string managed) { }
|
||||
|
||||
public byte* ToUnmanaged()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Free() { }
|
||||
}
|
||||
|
||||
public ref struct UnmanagedToManagedRef
|
||||
{
|
||||
public void FromManaged(string managed) { }
|
||||
|
||||
public void FromUnmanaged(byte* unmanaged)
|
||||
{
|
||||
}
|
||||
|
||||
public string ToManaged()
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public byte* ToUnmanaged()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Free() { }
|
||||
}
|
||||
|
||||
public ref struct UnmanagedToManagedIn
|
||||
{
|
||||
private byte* _unmanagedValue;
|
||||
|
||||
public void FromUnmanaged(byte* unmanaged)
|
||||
{
|
||||
_unmanagedValue = unmanaged;
|
||||
}
|
||||
|
||||
public string ToManaged()
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public void Free() { }
|
||||
}
|
||||
*/
|
||||
}
|
||||
Loading…
Reference in a new issue