Skip to content

Commit

Permalink
Add BSTR.Length property
Browse files Browse the repository at this point in the history
Closes #717
  • Loading branch information
AArnott committed Oct 13, 2022
1 parent 2cceaa6 commit 83b3dfb
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Microsoft.Windows.CsWin32/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4157,6 +4157,7 @@ private StructDeclarationSyntax DeclareTypeDefStruct(TypeDefinition typeDef, Typ
{
case "BSTR":
members = members.AddRange(this.CreateAdditionalTypeDefBSTRMembers());
members = members.AddRange(this.ExtractMembersFromTemplate(name.Identifier.ValueText));
break;
case "PWSTR":
members = members.AddRange(this.CreateAdditionalTypeDefPWSTRMembers());
Expand Down
7 changes: 7 additions & 0 deletions src/Microsoft.Windows.CsWin32/templates/BSTR.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
internal partial struct BSTR
{
/// <summary>
/// Gets the length of the BSTR in characters.
/// </summary>
internal unsafe int Length => this.Value is null ? 0 : checked((int)(*(((uint*)this.Value) - 1) / sizeof(char)));
}
23 changes: 23 additions & 0 deletions test/GenerationSandbox.Tests/BasicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,29 @@ public void BSTR_ToString_Null()
Assert.Null(bstr.ToString());
}

[Theory]
[InlineData("")]
[InlineData("h")]
[InlineData("hello")]
public void BSTR_Length(string value)
{
BSTR bstr = (BSTR)Marshal.StringToBSTR(value);
try
{
Assert.Equal(value.Length, bstr.Length);
}
finally
{
Marshal.FreeBSTR(bstr);
}
}

[Fact]
public void BSTR_Length_Null()
{
Assert.Equal(0, default(BSTR).Length);
}

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

0 comments on commit 83b3dfb

Please sign in to comment.