Skip to content
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
21 changes: 13 additions & 8 deletions src/Microsoft.Windows.CsWin32/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4325,16 +4325,21 @@ private IEnumerable<MemberDeclarationSyntax> CreateAdditionalTypeDefBSTRMembers(
{
ExpressionSyntax thisValue = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName("Value"));

// public override string ToString() => Marshal.PtrToStringBSTR(new IntPtr(this.Value));
// Marshal.PtrToStringBSTR(new IntPtr(this.Value))
InvocationExpressionSyntax ptrToStringBstr = InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(nameof(Marshal)),
IdentifierName(nameof(Marshal.PtrToStringBSTR))))
.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(ObjectCreationExpression(IntPtrTypeSyntax).WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(thisValue))))))));

// this.Value != null
ExpressionSyntax valueIsNotNull = BinaryExpression(SyntaxKind.NotEqualsExpression, thisValue, LiteralExpression(SyntaxKind.NullLiteralExpression));

// public override string ToString() => this.Value != null ? Marshal.PtrToStringBSTR(new IntPtr(this.Value)) : null;
yield return MethodDeclaration(PredefinedType(TokenWithSpace(SyntaxKind.StringKeyword)), Identifier(nameof(this.ToString)))
.AddModifiers(TokenWithSpace(SyntaxKind.PublicKeyword), TokenWithSpace(SyntaxKind.OverrideKeyword))
.WithExpressionBody(ArrowExpressionClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(nameof(Marshal)),
IdentifierName(nameof(Marshal.PtrToStringBSTR))))
.WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(ObjectCreationExpression(IntPtrTypeSyntax).WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(thisValue))))))))))
.WithExpressionBody(ArrowExpressionClause(ConditionalExpression(valueIsNotNull, ptrToStringBstr, LiteralExpression(SyntaxKind.NullLiteralExpression))))
.WithSemicolonToken(SemicolonWithLineFeed);

if (this.canUseSpan)
Expand Down
7 changes: 7 additions & 0 deletions test/GenerationSandbox.Tests/BasicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ public void BSTR_ToString()
}
}

[Fact]
public void BSTR_ToString_Null()
{
BSTR bstr = default;
Assert.Null(bstr.ToString());
}

[Fact]
public unsafe void BSTR_ImplicitConversionTo_ReadOnlySpan()
{
Expand Down