Skip to content

Avoid Unsafe.SkipInit API when it isn't available #1208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,20 @@ Install the `Microsoft.Windows.CsWin32` package:
dotnet add package Microsoft.Windows.CsWin32 --prerelease
```

You should also install the `System.Memory` package when targeting .NET Framework 4.5+ or .NET Standard 2.0,
as that adds APIs that significantly improve much of the code generated by CsWin32:
You should also install the `System.Memory` and `System.Runtime.CompilerServices.Unsafe` packages when targeting .NET Framework 4.5+ or .NET Standard 2.0,
as these add APIs that significantly improve much of the code generated by CsWin32:

```ps1
dotnet add package System.Memory
dotnet add package System.Runtime.CompilerServices.Unsafe
```

Projects targeting .NET Core 2.1+ or .NET 5+ do *not* need to add the `System.Memory` package reference,
Projects targeting .NET Core 2.1+ or .NET 5+ do *not* need to add these package references,
although it is harmless to do so.

Note that while the `System.Memory` package depends on the `System.Runtime.CompilerServices.Unsafe` package,
referencing the latter directly is still important to get the latest version of the APIs it provides.

Your project must allow unsafe code to support the generated code that will likely use pointers.
This does *not* automatically make all your code *unsafe*.
Use of the `unsafe` keyword is required anywhere you use pointers.
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.Windows.CsWin32/Generator.Features.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public partial class Generator
private readonly bool canUseUnsafeAsRef;
private readonly bool canUseUnsafeAdd;
private readonly bool canUseUnsafeNullRef;
private readonly bool canUseUnsafeSkipInit;
private readonly bool canUseUnmanagedCallersOnlyAttribute;
private readonly bool canUseSetLastPInvokeError;
private readonly bool unscopedRefAttributePredefined;
Expand Down
19 changes: 14 additions & 5 deletions src/Microsoft.Windows.CsWin32/Generator.InlineArrays.cs
Original file line number Diff line number Diff line change
Expand Up @@ -605,11 +605,20 @@ InvocationExpressionSyntax SliceAtNullToString(ExpressionSyntax readOnlySpan)
? MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, resultLocal, valueFieldName) // result.Value
: PrefixUnaryExpression(SyntaxKind.AddressOfExpression, MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, resultLocal, firstElementName!)); // &result._0

// Unsafe.SkipInit(out __char_1 result);
implicitSpanToStruct = implicitSpanToStruct.AddBodyStatements(
ExpressionStatement(InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName(nameof(Unsafe)), IdentifierName("SkipInit")),
ArgumentList().AddArguments(Argument(nameColon: null, Token(SyntaxKind.OutKeyword), DeclarationExpression(fixedLengthStructName.WithTrailingTrivia(Space), SingleVariableDesignation(resultLocal.Identifier)))))));
if (this.canUseUnsafeSkipInit)
{
// Unsafe.SkipInit(out __char_1 result);
implicitSpanToStruct = implicitSpanToStruct.AddBodyStatements(
ExpressionStatement(InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName(nameof(Unsafe)), IdentifierName("SkipInit")),
ArgumentList().AddArguments(Argument(nameColon: null, Token(SyntaxKind.OutKeyword), DeclarationExpression(fixedLengthStructName.WithTrailingTrivia(Space), SingleVariableDesignation(resultLocal.Identifier)))))));
}
else
{
implicitSpanToStruct = implicitSpanToStruct.AddBodyStatements(
LocalDeclarationStatement(VariableDeclaration(fixedLengthStructName)).AddDeclarationVariables(
VariableDeclarator(resultLocal.Identifier).WithInitializer(EqualsValueClause(DefaultExpression(fixedLengthStructName)))));
}

// x.Slice(initLength, Length - initLength).Clear();
StatementSyntax ClearSlice(ExpressionSyntax span) =>
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.Windows.CsWin32/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public Generator(string metadataLibraryPath, Docs? docs, GeneratorOptions option
this.canUseUnsafeAsRef = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("Add").Any() is true;
this.canUseUnsafeAdd = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("AsRef").Any() is true;
this.canUseUnsafeNullRef = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("NullRef").Any() is true;
this.canUseUnsafeSkipInit = this.compilation?.GetTypeByMetadataName(typeof(Unsafe).FullName)?.GetMembers("SkipInit").Any() is true;
this.canUseUnmanagedCallersOnlyAttribute = this.compilation?.GetTypeByMetadataName("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute") is not null;
this.canUseSetLastPInvokeError = this.compilation?.GetTypeByMetadataName("System.Runtime.InteropServices.Marshal")?.GetMembers("GetLastSystemError").IsEmpty is false;
this.unscopedRefAttributePredefined = this.FindTypeSymbolIfAlreadyAvailable("System.Diagnostics.CodeAnalysis.UnscopedRefAttribute") is not null;
Expand Down
6 changes: 5 additions & 1 deletion src/Microsoft.Windows.CsWin32/readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ as that adds APIs that significantly improve much of the code generated by CsWin

```ps1
dotnet add package System.Memory
dotnet add package System.Runtime.CompilerServices.Unsafe
```

Projects targeting .NET Core 2.1+ or .NET 5+ do *not* need to add the `System.Memory` package reference,
Projects targeting .NET Core 2.1+ or .NET 5+ do *not* need to add these package references,
although it is harmless to do so.

Note that while the `System.Memory` package depends on the `System.Runtime.CompilerServices.Unsafe` package,
referencing the latter directly is still important to get the latest version of the APIs it provides.

Your project must allow unsafe code to support the generated code that will likely use pointers.

Learn more from our README on GitHub: https://github.com/microsoft/CsWin32#readme
27 changes: 27 additions & 0 deletions test/Microsoft.Windows.CsWin32.Tests/InlineArrayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,33 @@ public void FixedLengthInlineArray(
this.AssertNoDiagnostics();
}

[Theory, CombinatorialData]
public async Task UnsafeApiReferencesOnlyWhenAvailable(
bool referenceUnsafe,
bool referenceMemory,
[CombinatorialValues("net35", "net472", "netstandard2.0")] string tfm)
{
ReferenceAssemblies referenceAssemblies = tfm switch
{
"net35" => ReferenceAssemblies.NetFramework.Net35.WindowsForms,
"net472" => ReferenceAssemblies.NetFramework.Net472.WindowsForms,
"netstandard2.0" => ReferenceAssemblies.NetStandard.NetStandard20,
_ => throw new ArgumentOutOfRangeException(nameof(tfm)),
};
if (referenceUnsafe)
{
referenceAssemblies = referenceAssemblies.AddPackages([MyReferenceAssemblies.ExtraPackages.Unsafe]);
}

if (referenceMemory)
{
referenceAssemblies = referenceAssemblies.AddPackages([MyReferenceAssemblies.ExtraPackages.Memory]);
}

this.compilation = await this.CreateCompilationAsync(referenceAssemblies, Platform.AnyCpu);
this.GenerateApi("THUMBBUTTON");
}

[Theory, PairwiseData]
public void FixedLengthInlineArray_Pointers(
bool allowMarshaling,
Expand Down
13 changes: 10 additions & 3 deletions test/Microsoft.Windows.CsWin32.Tests/MyReferenceAssemblies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ internal static class MyReferenceAssemblies
new PackageIdentity("Microsoft.Windows.SDK.Contracts", "10.0.22621.2428"));

private static readonly ImmutableArray<PackageIdentity> AdditionalModernPackages = AdditionalLegacyPackages.AddRange(ImmutableArray.Create(
new PackageIdentity("System.Runtime.CompilerServices.Unsafe", "6.0.0"),
new PackageIdentity("System.Memory", "4.5.5"),
new PackageIdentity("Microsoft.Win32.Registry", "5.0.0")));
ExtraPackages.Unsafe,
ExtraPackages.Memory,
ExtraPackages.Registry));

internal static readonly ReferenceAssemblies NetStandard20 = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(AdditionalModernPackages);
#pragma warning restore SA1202 // Elements should be ordered by access
Expand All @@ -26,4 +26,11 @@ internal static class Net
internal static readonly ReferenceAssemblies Net60 = ReferenceAssemblies.Net.Net60.AddPackages(AdditionalModernPackages);
internal static readonly ReferenceAssemblies Net70 = ReferenceAssemblies.Net.Net70.AddPackages(AdditionalModernPackages);
}

internal static class ExtraPackages
{
internal static readonly PackageIdentity Unsafe = new PackageIdentity("System.Runtime.CompilerServices.Unsafe", "6.0.0");
internal static readonly PackageIdentity Memory = new PackageIdentity("System.Memory", "4.5.5");
internal static readonly PackageIdentity Registry = new PackageIdentity("Microsoft.Win32.Registry", "5.0.0");
}
}
Loading