Skip to content
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

Generate cocreatable types as classes with [ComImport] #454

Merged
merged 1 commit into from
Nov 23, 2021
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
28 changes: 28 additions & 0 deletions src/Microsoft.Windows.CsWin32/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2588,6 +2588,10 @@ private bool IsCompilerGenerated(TypeDefinition typeDef)
{
typeDeclaration = this.DeclareTypeDefStruct(typeDef);
}
else if (this.IsEmptyStructWithGuid(typeDef))
{
typeDeclaration = this.DeclareCocreatableClass(typeDef);
}
else
{
StructDeclarationSyntax structDeclaration = this.DeclareStruct(typeDef);
Expand Down Expand Up @@ -2635,6 +2639,12 @@ private bool IsCompilerGenerated(TypeDefinition typeDef)

private bool IsTypeDefStruct(TypeDefinition typeDef) => typeDef.GetCustomAttributes().Any(att => this.IsAttribute(this.Reader.GetCustomAttribute(att), InteropDecorationNamespace, NativeTypedefAttribute));

private bool IsEmptyStructWithGuid(TypeDefinition typeDef)
{
return typeDef.GetCustomAttributes().Any(att => this.IsAttribute(this.Reader.GetCustomAttribute(att), InteropDecorationNamespace, nameof(GuidAttribute)))
&& typeDef.GetFields().Count == 0;
}

private void DeclareExternMethod(MethodDefinitionHandle methodDefinitionHandle)
{
MethodDefinition methodDefinition = this.Reader.GetMethodDefinition(methodDefinitionHandle);
Expand Down Expand Up @@ -3427,6 +3437,24 @@ private StructDeclarationSyntax DeclareStruct(TypeDefinition typeDef)
return result;
}

/// <summary>
/// Creates an empty class that when instantiated, creates a cocreatable Windows object
/// that may implement a number of interfaces at runtime, discoverable only by documentation.
/// </summary>
private ClassDeclarationSyntax DeclareCocreatableClass(TypeDefinition typeDef)
{
IdentifierNameSyntax name = IdentifierName(this.Reader.GetString(typeDef.Name));
Guid guid = this.FindGuidFromAttribute(typeDef) ?? throw new ArgumentException("Type does not have a GuidAttribute.");
var classModifiers = TokenList(TokenWithSpace(this.Visibility));
classModifiers = classModifiers.Add(TokenWithSpace(SyntaxKind.PartialKeyword));
ClassDeclarationSyntax result = ClassDeclaration(name.Identifier)
.WithModifiers(classModifiers)
.AddAttributeLists(AttributeList().AddAttributes(GUID(guid), ComImportAttribute));

result = this.AddApiDocumentation(name.Identifier.ValueText, result);
return result;
}

/// <summary>
/// Creates a struct that emulates a typedef in the C language headers.
/// </summary>
Expand Down
10 changes: 10 additions & 0 deletions test/GenerationSandbox.Tests/BasicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
using Windows.Win32.Foundation;
using Windows.Win32.Media.DirectShow;
using Windows.Win32.Storage.FileSystem;
using Windows.Win32.System.Com;
using Windows.Win32.System.Console;
using Windows.Win32.System.ErrorReporting;
using Windows.Win32.UI.Shell;
using Xunit;
using Xunit.Abstractions;

Expand Down Expand Up @@ -428,4 +430,12 @@ public void CHAR_MarshaledAsUtf8()
{
Assert.Equal(1, Marshal.SizeOf<CHAR>());
}

[Fact]
public void CocreatableClassesWithImplicitInterfaces()
{
ShellLink shellLink = new ShellLink();
IPersistFile persistFile = (IPersistFile)shellLink;
Assert.NotNull(persistFile);
}
}
4 changes: 3 additions & 1 deletion test/GenerationSandbox.Tests/NativeMethods.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ GetWindowText
GetWindowTextLength
HDC_UserSize
IEnumDebugPropertyInfo
IPersistFile
KEY_EVENT_RECORD
LoadLibrary
MainAVIHeader
NTSTATUS
RegLoadAppKey
RM_PROCESS_INFO
ShellLink
WER_REPORT_INFORMATION
wglGetProcAddress
WPARAM
RegLoadAppKey
11 changes: 11 additions & 0 deletions test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2227,6 +2227,17 @@ public async Task UnparseableNativeMethodsJson()
}.RunAsync();
}

[Fact]
public void CocreatableStructs()
{
this.generator = this.CreateGenerator();
Assert.True(this.generator.TryGenerate("ShellLink", CancellationToken.None));
this.CollectGeneratedCode(this.generator);
this.AssertNoDiagnostics();
ClassDeclarationSyntax classDecl = Assert.IsType<ClassDeclarationSyntax>(this.FindGeneratedType("ShellLink").Single());
Assert.Contains(classDecl.AttributeLists, al => al.Attributes.Any(a => a.Name.ToString().Contains("ComImport")));
}

private static string ConstructGlobalConfigString(bool omitDocs = false)
{
StringBuilder globalConfigBuilder = new();
Expand Down