-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
CsWin32 usage sample #7929
CsWin32 usage sample #7929
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Runtime.CompilerServices; | ||
|
||
[assembly: InternalsVisibleTo("WindowsBase, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"$schema": "https://aka.ms/CsWin32.schema.json", | ||
"allowMarshaling": false, | ||
"useSafeHandles": false, | ||
"comInterop": { | ||
"preserveSigMethods": [ | ||
"*" | ||
] | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
AC_SRC_* | ||
BI_COMPRESSION | ||
BITMAPINFO | ||
CLSID_WICImagingFactory | ||
CoCreateInstance | ||
CoInitialize | ||
CreateCompatibleDC | ||
CreateDIBSection | ||
CreateWindowEx | ||
DefWindowProc | ||
DeleteObject | ||
DestroyWindow | ||
DwmIsCompositionEnabled | ||
E_NOINTERFACE | ||
E_POINTER | ||
GetDC | ||
GetSystemMetrics | ||
GUID_WICPixelFormat32bppPBGRA | ||
IsWindow | ||
IWICImagingFactory | ||
RegisterClassEx | ||
ReleaseDC | ||
S_OK | ||
SelectObject | ||
UnregisterClass | ||
UpdateLayeredWindow | ||
WIN32_ERROR | ||
WINCODEC_SDK_VERSION1 |
Original file line number | Diff line number | Diff line change | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,35 @@ | ||||||||||||
<Project Sdk="Microsoft.NET.Sdk"> | ||||||||||||
|
||||||||||||
<PropertyGroup> | ||||||||||||
<AssemblyName>System.Windows.Primitives</AssemblyName> | ||||||||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||||||||||||
<CLSCompliant>false</CLSCompliant> | ||||||||||||
<Nullable>enable</Nullable> | ||||||||||||
<Platforms>AnyCPU</Platforms> | ||||||||||||
|
||||||||||||
<!-- | ||||||||||||
We align casing and naming with Win32 API. As such some types have all lower case names, which | ||||||||||||
in theory may conflict with new C# keywords in the future. Our types here are internal so end | ||||||||||||
users won't be impacted. If some name becomes difficult to adapt to with the @ symbol we can | ||||||||||||
cross that bridge when we hit it (if ever). | ||||||||||||
--> | ||||||||||||
<NoWarn>$(NoWarn);CS8981;CS3016</NoWarn> | ||||||||||||
<!-- | ||||||||||||
We don't care about CLS compliance since everything here is internal and we want to match native types. | ||||||||||||
--> | ||||||||||||
<NoWarn>$(NoWarn);CS3016</NoWarn> | ||||||||||||
<Deterministic>true</Deterministic> | ||||||||||||
<ProduceReferenceAssembly>true</ProduceReferenceAssembly> | ||||||||||||
<UsePublicApiAnalyzers>true</UsePublicApiAnalyzers> | ||||||||||||
<RootNamespace /> | ||||||||||||
</PropertyGroup> | ||||||||||||
|
||||||||||||
<ItemGroup> | ||||||||||||
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.5-beta"> | ||||||||||||
<PrivateAssets>all</PrivateAssets> | ||||||||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||||||||||||
</PackageReference> | ||||||||||||
Comment on lines
+28
to
+31
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" /> | ||||||||||||
</ItemGroup> | ||||||||||||
|
||||||||||||
</Project> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Runtime.CompilerServices; | ||
using Windows.Win32.System.Com; | ||
|
||
namespace Windows.Win32.Foundation; | ||
|
||
/// <summary> | ||
/// Lifetime management struct for a native COM pointer. Meant to be utilized in a <see langword="using"/> statement | ||
JeremyKuhne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// to ensure <see cref="IUnknown.Release"/> is called when going out of scope with the using. | ||
/// </summary> | ||
/// <remarks> | ||
/// <para> | ||
/// This struct has implicit conversions to T** and void** so it can be passed directly to out methods. | ||
/// For example: | ||
/// </para> | ||
/// <code> | ||
/// using ComScope<IUnknown> unknown = new(null); | ||
/// comObject->QueryInterface(&iid, unknown); | ||
/// </code> | ||
/// <para> | ||
/// Take care to NOT make copies of the struct to avoid accidental over-release. | ||
/// </para> | ||
Comment on lines
+23
to
+25
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Roslyn's There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you provide more information on where this attribute is defined and which analyzer package needs to be installed to leverage it? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's part of Roslyn.Diagnostics.Analyzers today: It's fairly unforgiving. Any use of a non-copyable value which doesn't match a known non-copying value will produce a diagnostic. It also relies on IOperation, so I'm not sure if it handles all cases where a piece of syntax doesn't have IOperation support. In practice, it's worked well for us with minimal hassle. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'll look into it, thanks. |
||
/// </remarks> | ||
/// <typeparam name="T"> | ||
/// This should be one of the struct COM definitions as generated by CsWin32. Ideally we'd constrain to | ||
/// <see cref="IUnknown.Interface"/> or some other interface tag to enforce that this is being used around | ||
/// a struct that is actually a COM wrapper. | ||
JeremyKuhne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// </typeparam> | ||
internal readonly unsafe ref struct ComScope<T> where T : unmanaged, IComIID | ||
JeremyKuhne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Keeping internal as nint allows us to use Unsafe methods to get significantly better generated code. | ||
private readonly nint _value; | ||
public T* Value => (T*)_value; | ||
public IUnknown* AsUnknown => (IUnknown*)_value; | ||
|
||
public ComScope(T* value) => _value = (nint)value; | ||
|
||
// Can't add an operator for IUnknown* as we have ComScope<IUnknown>. | ||
|
||
public static implicit operator T*(in ComScope<T> scope) => (T*)scope._value; | ||
|
||
public static implicit operator void*(in ComScope<T> scope) => (void*)scope._value; | ||
|
||
public static implicit operator nint(in ComScope<T> scope) => scope._value; | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static implicit operator T**(in ComScope<T> scope) => (T**)Unsafe.AsPointer(ref Unsafe.AsRef(scope._value)); | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static implicit operator void**(in ComScope<T> scope) => (void**)Unsafe.AsPointer(ref Unsafe.AsRef(scope._value)); | ||
|
||
public bool IsNull => _value == 0; | ||
|
||
public ComScope<TTo> TryQuery<TTo>(out HRESULT hr) where TTo : unmanaged, IComIID | ||
{ | ||
ComScope<TTo> scope = new(null); | ||
hr = ((IUnknown*)Value)->QueryInterface(IID.Get<TTo>(), scope); | ||
return scope; | ||
} | ||
|
||
/// <summary> | ||
/// Attempt to create a <see cref="ComScope{T}"/> from the given COM interface. | ||
/// </summary> | ||
public static ComScope<T> TryQueryFrom<TFrom>(TFrom* from, out HRESULT hr) where TFrom : unmanaged, IComIID | ||
{ | ||
ComScope<T> scope = new(null); | ||
hr = from is null ? HRESULT.E_POINTER : ((IUnknown*)from)->QueryInterface(IID.Get<T>(), scope); | ||
return scope; | ||
} | ||
|
||
/// <summary> | ||
/// Create a <see cref="ComScope{T}"/> from the given COM interface. Throws on failure. | ||
/// </summary> | ||
public static ComScope<T> QueryFrom<TFrom>(TFrom* from) where TFrom : unmanaged, IComIID | ||
{ | ||
if (from is null) | ||
{ | ||
HRESULT.E_POINTER.ThrowOnFailure(); | ||
} | ||
|
||
ComScope<T> scope = new(null); | ||
((IUnknown*)from)->QueryInterface(IID.Get<T>(), scope).ThrowOnFailure(); | ||
return scope; | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
IUnknown* unknown = (IUnknown*)_value; | ||
|
||
// Really want this to be null after disposal to avoid double releases, but we also want | ||
// to maintain the readonly state of the struct to allow passing as `in` without creating implicit | ||
// copies (which would break the T** and void** operators). | ||
JeremyKuhne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*(void**)this = null; | ||
if (unknown is not null) | ||
{ | ||
unknown->Release(); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
|
||
namespace Windows.Win32.Foundation; | ||
|
||
internal static unsafe class IID | ||
{ | ||
private static ref readonly Guid IID_NULL | ||
{ | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
get | ||
{ | ||
ReadOnlySpan<byte> data = new byte[] | ||
{ | ||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 | ||
}; | ||
|
||
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); | ||
} | ||
} | ||
|
||
// We cast away the "readonly" here as there is no way to communicate that through a pointer and | ||
// Marshal APIs take the Guid as ref. Even though none of our usages actually change the state. | ||
|
||
/// <summary> | ||
/// Gets a pointer to the IID <see cref="Guid"/> for the given <typeparamref name="T"/>. | ||
/// </summary> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static Guid* Get<T>() where T : unmanaged, IComIID | ||
=> (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in T.Guid)); | ||
|
||
/// <summary> | ||
/// Gets a reference to the IID <see cref="Guid"/> for the given <typeparamref name="T"/>. | ||
/// </summary> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static ref Guid GetRef<T>() where T : unmanaged, IComIID | ||
=> ref Unsafe.AsRef(in T.Guid); | ||
|
||
/// <summary> | ||
/// Empty <see cref="Guid"/> (GUID_NULL in docs). | ||
/// </summary> | ||
public static Guid* NULL() => (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in IID_NULL)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Applying
[assembly: CLSCompliant(false)]
will disable this warning and disable CLS compliance analysis which significantly improves compiler performance.