CsWin32: Emit warning/error when System.Memory reference is missing but required by emitted code

Actual behavior

As soon as I add ‘CharLower’ to my NativeMethods.txt I get the following build error:

Error	CS0246	The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?)
C:\dev\_tests\ConsoleApp3\Microsoft.Windows.CsWin32\Microsoft.Windows.CsWin32.SourceGenerator\PWSTR.g.cs

Other methods like ‘MFStartup’ which don’t take strings work fine.

Expected behavior

The project should compile without errors even if using .NET Framework v4.8 / netstandard2.0

Repro steps

  1. Create new .NET Framework 4.8 project or create .NET 5.0 project and change target framework to ‘net48’ or ‘netstandard2.0’.

  2. NativeMethods.txt content:

CharLower
  1. NativeMethods.json content (if present): does not exist

  2. Build project

Context

  • CsWin32 version: 0.1.422-beta
  • Win32Metadata version (if explicitly set by project): default
  • Target Framework: net48 or netstandard2.0
  • LangVersion: 8.0

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 15 (10 by maintainers)

Most upvoted comments

The problem is the IncludeAssets metadata leaving out compile. That does exactly what it’s supposed to (leaving System.Memory off as a reference) but it isn’t what we want. I’ll explore why VS is omitting this by default.

I also repro the issue when copying the PackageReference string from the NuGet website, which (compared to Visual Studio) does not include the buildtransitive flag:

<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.1.422-beta">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>

That repros for me. The issue comes from <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> inside the package reference. This is boilerplate that .NET tooling pushes hard for packages that are development dependencies. I always remove it:

  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.CsWin32" Version="0.1.422-beta" PrivateAssets="all" />
  </ItemGroup>

After that, you get error CS8805: Program using top-level statements must be an executable. because the project is missing <OutputType>.

A workaround might be to add this to your csproj:

    <PackageReference Include="System.Memory" Version="4.5.4" />