Skip to content

Commit

Permalink
take advantage of SpanMarshalling for ADsGetLastError
Browse files Browse the repository at this point in the history
suggested by review comment #93722 (comment)
  • Loading branch information
chrisdcmoore committed Oct 29, 2023
1 parent 1428673 commit 497bbb6
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
internal static partial class Activeds
{
[LibraryImport(Libraries.Activeds, StringMarshalling = StringMarshalling.Utf16)]
internal static unsafe partial int ADsGetLastError(out int error, char* errorBuffer, int errorBufferLength, char* nameBuffer, int nameBufferLength);
[LibraryImport(Libraries.Activeds)]
internal static partial int ADsGetLastError(out int error, Span<char> errorBuffer, int errorBufferLength, Span<char> nameBuffer, int nameBufferLength);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,15 @@ internal static Exception CreateFormattedComException(int hr)
return CreateFormattedComException(new COMException(errorMsg, hr));
}

internal static unsafe Exception CreateFormattedComException(COMException e)
internal static Exception CreateFormattedComException(COMException e)
{
// get extended error information
const int ErrorBufferLength = 256;
char* errorBuffer = stackalloc char[ErrorBufferLength];
char nameBuffer = '\0';
Span<char> errorBuffer = stackalloc char[ErrorBufferLength];

Span<char> nameBuffer = Span<char>.Empty;
int error = 0;
Interop.Activeds.ADsGetLastError(out error, errorBuffer, ErrorBufferLength, &nameBuffer, 0);
Interop.Activeds.ADsGetLastError(out error, errorBuffer, errorBuffer.Length, nameBuffer, nameBuffer.Length);

if (error != 0)
return new DirectoryServicesCOMException(new string(errorBuffer), error, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,11 +401,12 @@ private void CleanLastError()
Interop.Activeds.ADsSetLastError(Interop.Errors.ERROR_SUCCESS, null, null);
}

private unsafe int GetLastError(ref int errorCode)
private int GetLastError(ref int errorCode)
{
char c1 = '\0', c2 = '\0';
Span<char> errorBuffer = Span<char>.Empty;
Span<char> nameBuffer = Span<char>.Empty;
errorCode = Interop.Errors.ERROR_SUCCESS;
return Interop.Activeds.ADsGetLastError(out errorCode, &c1, 0, &c2, 0);
return Interop.Activeds.ADsGetLastError(out errorCode, errorBuffer, errorBuffer.Length, nameBuffer, nameBuffer.Length);
}
}
}
Expand Down

0 comments on commit 497bbb6

Please sign in to comment.