8000 Update API to use Native-Sized Integers · Issue #387 · dotnet/Silk.NET · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Update API to use Native-Sized Integers #387
Closed
@thargy

Description

@thargy

Summary of feature

C# 9 added support for native-sized integers as a drop-in replacements for IntPtr (and UIntPtr). The new native-sized intger types, nint and nuint, were added specifically to improve the experience of coding for interop scenarios, e.g. by low-level library authors, of which Silk.Net is a prime example. By changing our references to IntPtr and UIntPtr to nint and nuint respectively, consumers using C#9.0 will be pointed towards the new types and will benefit from the improvements provided.

Further, Silk.Net internal development will benefit by being less verbose.

Comments

After reviewing the implementation, the 2 new types are effectively implemented as syntatic sugar over IntPr and UIntPtr, with a new attribute NativeIntegerAttribute marking instances of the type for code compiled using C#9.0+. As such, library consumers on an older version of C# should continue to see the API as exposing IntPtr and UIntPtr and there shouldn't be any breaking changes introduced.

Following this change, code such as:

    public unsafe IntPtr Add(IntPtr a, IntPtr b)
    {
        return (IntPtr)(void*)((long)a + (long)b);
    }
  • which assumes a 64-bit architecture, can instead be written safely as:
	public nint Add(nint a, nint b) => a + b;

So long as the consumer is using C#9.0+.

Note this code can be called using IntPtr's due to implicit casting, e.g.:

	public IntPtr Test(IntPtr a, IntPtr b) => Add(a, b);

Will continue to work, allowing the API to be backwards compatible.

It would be useful to introduce the change in a preview build, after initial careful testing, to see if it causes any issues for existing consumers.

Alternatives

It is also plausible to not make this change at all. Consumers can then optionally perform the casting themselves. The only downside is the reduced discoverability of the new modern types, as there shouldn't be any real performance impact of casting, for example, the following is valid:

    public unsafe IntPtr AddP(IntPtr a, IntPtr b) => (IntPtr)(void*)((long)a + (long)b); 
    public nint Add(nint a, nint b) => AddP(a,b);

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0