Search code examples
c#.netcompiler-errorsinterop.net-7.0

Unexpected compiler error whilst using new .NET LibraryImport attribute


I am trying to upgrade older code to support the latest features in .NET 7, namely LibraryImport, but I am having trouble with errors that others don't seem to have. All examples I can find require the method to be both static and partial, but without extern it demands an implementation.

#if NET7_0_OR_GREATER
            [LibraryImport("kernel32")]
            public static partial IntPtr LoadLibrary(string fileName);

            [LibraryImport("kernel32")]
            public static partial IntPtr GetProcAddress(IntPtr module, string procName);

            [LibraryImport("kernel32")]
            public static partial int FreeLibrary(IntPtr module);
#else

The error is as follows: "Partial method 'IntPtr LoadLibrary(string)' must have an implementation part because it has accessibility modifiers." The only suggestion just removed partial and added a generic implementation that threw an exception when called.

At first, I thought I was having issues because my project supported multiple frameworks, but the error persisted on a fresh .NET 7 console application. I even tried using another IDE, but it didn't help.

What exactly is wrong with my code?


Solution

  • The compiler gets quite noisy when it comes to source generators, so the error you see may not be of much trust. Analyzer crashes are pretty common, so it's possible that you see an error that was relevant at the moment you were writing the code and not when you finished. Problems with Intellisense are also admitted in docs:

    You might need to restart Visual Studio to see IntelliSense and get rid of errors as the tooling experience is actively being improved.

    However, there are some things that you should consider:

    • As source generation generates partial implementation inside the class where your stub is declared, the class itself has to be partial.

    • LibraryImport requires unsafe attribute to be allowed in the project code.

    • The compiler wants to know how to marshal string arguments. It won't let you compile without that information.

    If the problem persists, take a look at the generated files in Visual Studio. You can do this in Solution Explorer -> {your project} -> Dependencies -> Analyzers -> Microsoft.Interop.LibraryImportGenerator -> Microsoft.Interop.LibraryImportGenerator -> LibraryImports.g.cs

    Note: there is not such an entry in kernel32 as LoadLibrary. There is LoadLibraryA and LoadLibraryW (isn't relevant to your building error, but it will throw in runtime)