Repository navigation
Description
Rationale
There exists a few common interchange types which are variable sized. Unlike many of the other types, it is non-trivial for a user to define these types themselves and even if they did, there are some calling conventions where structs are not marshaled the same as the underlying T they may wrap.
These types include long and unsigned long types defined by C/C++ which have variable size depending on the target platform/architecture. On Windows, these types are always 4-bytes and are equivalent to int/uint in C#. On Unix, however, these types are 4-bytes or 8-bytes depending on if you are targeting a 32-bit or 64-bit platform which makes them equivalent to nint/nuint.
Likewise Apple defines CGFloat which is float on 32-bit systems and double on 64-bit systems.
As such, I propose we expose minimal types that are recognized by the runtime and are handled as if they were the corresponding underlying primitive type to avoid the ABI issues. These types are explicitly very minimal and do not provide "common" operations such as parsing, formatting, or even simple operators.
Proposal
namespace System.Runtime.InteropServices
{
public readonly struct CLong : IEquatable<CLong>
{
public CLong(nint value);
public nint Value { get; }
public override bool Equals(object o);
public bool Equals(CLong other);
public override int GetHashCode();
public override string ToString();
}
public readonly struct CULong : IEquatable<CULong>
{
public CULong(nuint value);
public nuint Value { get; }
public override bool Equals(object o);
public bool Equals(CULong other);
public override int GetHashCode();
public override string ToString();
}
public readonly struct NFloat : IEquatable<NFloat>
{
public NFloat(double value);
public double Value { get; }
public override bool Equals(object o);
public bool Equals(NFloat other);
public override int GetHashCode();
public override string ToString();
}
}
Activity
tannergooding commentedon Nov 12, 2019
CC. @jkoritzinsky, @AaronRobinsonMSFT, @jkotas for thoughts/opinions/etc.
tannergooding commentedon Nov 12, 2019
It does look like there is one unused bit on
StructLayoutforLayoutKind, so it would also be possible to haveStructLayout(LayoutKind.Transparent), for example, as an alternative proposal.GrabYourPitchforks commentedon Nov 12, 2019
Would something like the below also make sense?
FiniteReality commentedon Nov 12, 2019
How would this work for pointers, which are based on the native platform word size? Some native libraries, such as DirectX, have APIs which take arrays of pointers. It's hard to accept parameters like that as
Span<T>does not support pointer types as T, so it's somewhat common to see code like this:Passing these values as
Span<T>is then possible, as you can useSpan<Pointer<T>>jkotas commentedon Nov 13, 2019
We have number of similar suggestions to add more rules for generating interop marshallers (e.g. one for
Span<T>- https://github.com/dotnet/coreclr/issues/14460) or to fix bugs in existing interop marshallers. My preference would be to implement these new rules using a build-time interop source generator only. It would create incentive for projects to switch to build-time generated interop and help us avoid all problems with runtime-generated interop that we have today (startup performance, version resilient AOT, compatibility, diagnosability and ease of maintenance).Once we have a built-time generated interop, I would be open to add as many of these new marshaling rules as necessary.
tannergooding commentedon Nov 13, 2019
I'm not sure that will be a sufficient way to go about this. There are a large number of interop libraries in existence today, some of which are purposefully exposing bindings in a particular way and which may not be able to change due to it being breaking or due to it being non-trivial effort.
You likewise have cases where there is a lot of customization and/or configurability desired. For example:
SIZE_Tasnuint, orHWND__asIntPtr)tagPOINTtoPOINTorD3DCOLORVALUEtoDXGI_RGBA)While I think having some sort of source generator to assist with this would be nice, and while there are many existing tools that help with the binding generation process (ClangSharp, CppAst, etc); they will almost always need some kind of manual fixups, customization, etc. They also all, today, use existing interop mechanisms exposed through
System.Runtime.InteropServicesand would likely need to continue doing so in the future as well (even any generated by some future "offficial" binding generator).jkotas commentedon Nov 13, 2019
I am not suggesting that we should invent universal interop source generator. I agree that it is close to impossible to build such thing. Let me change my statement to: "I would be open to add as many of these new marshaling rules as reasonable.".
This is what you can write today:
This proposal would let you avoid a bit of the boiler plate code and instead write:
My point is that boiler plate code generator should run at build time. Runtime is not a good place for it.
tannergooding commentedon Nov 13, 2019
So basically your proposal is the user would write the latter and then some build time tool (possibly C# source generators or an IL rewriter, so other languages can also benefit) would convert it to the former; Is that correct?
I'd be interested in hearing the proposal for how that would work with function pointers and delegates, although I could conceive of that being handled by wrappers as well.
I'd imagine there would also be a fairly long tail of bugs around ensuring the JIT produced good codegen for these scenarios (but fixing those would help with better codegen in the JIT overall, not just for interop).
jkotas commentedon Nov 13, 2019
I expect that this would have better performance from the get-go (both startup performance and throughput). The marshaling IL generated by the runtime today is no different from what you can write in C#. However:
booltoBOOL.[-]Expose a new UnmanagedType: TransparentStruct[/-][+]Expose a new TransparentStruct attribute and CLong/CULong interchange types[/+]tannergooding commentedon Apr 22, 2020
Updated the proposal based on the discussion that has been happening on #27530 (comment)
[-]Expose a new TransparentStruct attribute and CLong/CULong interchange types[/-][+]Expose CLong, CULong, and NFloat interchange types[/+]34 remaining items
tannergooding commentedon Nov 16, 2020
That is what the
CLongandCULongtypes are. I don't think thenprefix is better forlongand/orulongin this context. They are in no way tied to the native platform/architecture likenint,nuint, ornfloatare and are instead tied to how the underlying ABI handles the correspondingly named types from theCprogramming language.ceztko commentedon Nov 16, 2020
"No way" seems too bold here when actually C/C++
longhas a scaling semantics that behaves exactly likenintin all Unix .NET supported ABIs. My opinion here is that in the long run over detailed naming scheme hurts eyes, andc/Cprefixes are not that fantastic choice that makes them appear like they are the perfect fit.nprefix would have the advantage of grouping all the types that have special meaning with regard to runtime architecture and ABIs. Also consider how the verynprefix is probably already a compromise when used fornfloat: there's no correlation to FPU registers size compared to what happens for integral types (FP registers are most often 80bit sizes), and calling it "native" gives the wrong feeling that is the right type to use for general math in all architectures, which of course it's not true. Still I take thenchoice innfloatas an acceptable, and understandable, compromise.DeafMan1983 commentedon Nov 16, 2020
Oh my god powerful teacher, @ceztko ! Good job! Linux/Unix or BSD are very different to MS-DOS. Why does young Bill Gates work hard since initial Windows Operating System with 32Bit like C/C++ formation. Is it correctly?
Since my birth C++ releases initial and it works for Unix Format too. Mathematics failed to mean 64 or 32 for long.That's why I understand that now. OK we need with nint, nuint, nfloat, nshort etc for C# Unix-Net.
tannergooding commentedon Nov 16, 2020
While it does match the behavior for Unix platforms which are
LP64, it does not match Windows, which isLLP64(longis always 32-bits`)."native" in this context doesn't mean register size, which might even be 128 or more bits on some platforms. It means it matches the bitness of the underlying platform, so either 32 or 64-bits and is ultimately just extending an existing concept.
With regards to the C
longandunsigned longkeywords: If you are only supportingUnix, then usingnintandnuintare ultimately better. If you are only supporting Windows, thenintis better.CLongandCULongwill ultimately just be interchange types with no operator support for the scenarios where you need to support bindings for both Unix and Windows simultaneously and where the C library (for whatever reason) decided to uselongon both.This scenario arises quite frequently in code that was ported to Windows before the 64-bit split and less commonly after where codebases often use
intptr_tanduintptr_tinstead to ensure consistent behavior and usability. However, it does still crop up from time to time, such as with several of thelibClangbindings.ceztko commentedon Nov 16, 2020
@tannergooding thank you for continuing the discussion. Actually there was no need to re-instantiate explanation for your proposed
CLong/CULongtypes which is was already clear to me. I just said that I don't likec/Cand I suggested to make it easy and prefix all possibly scaling types withnand specify implementation details and rationale in the documentation. In the end, I guess you'll have internally a committee at Microsoft and have a resolution later on names of these types. Since I am not going to take part at this committee I just wanted to leave my feedback. That's all.AaronRobinsonMSFT commentedon Nov 16, 2020
The API review was already done and referenced above at #13788 (comment). Everyone is welcome to participate in those reviews as they are public, this was already happened unfortunately. Thank you for sharing your feedback through it is much appreciated.
markusschaber commentedon Nov 19, 2020
Just as an anecdote: In our case, it's an existing, historically grown C API/ABI with roots about 25 years in the past. Back then, 64 bit for Desktop (Windows, Linux) was in the far future, and even more in the dozen or so embedded platforms which are our main target. As there's also a C++ API using the same structs and datatypes, the use of "long" also could not be upgraded to modern types like "int32_t" or "ptrsize_t" without breaking ABI compatibility for C++ clients.
GSPP commentedon Dec 30, 2020
This looks like something that would benefit from a proof of concept to validate the design. For example, I notice that there are no conversion operators. The types are intentionally minimal. I wonder how well this works under practical circumstances. I also wonder if this feature carries it's weight. In this issue, there was pretty minimal discussion around that. Maybe this discussion happened elsewhere?
ssa3512 commentedon Dec 30, 2020
@GSPP my understanding (and need) is that these really are only for use in cross platform private interop methods. You would never expose them in a public API - you would instead expose
intorlongor some other result in the public surface. This was discussed in the API review video linked hereAaronRobinsonMSFT commentedon Dec 31, 2020
Correct. Exposing these to users would be rather annoying and represent a leak in the API abstraction being exposed. The primary purpose here is to help interop do the right thing when it concerns cross platform APIs that use a C/C++
longon the native side.