You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Feature Request: Variable-size "long" for simplified p/invoke #27530
To greatly simplify p/invoke code (particularly struct definitions, but also method signatures), it would be amazing if there was a "long" type that matched the OS's compiler definition of long. This would mean no more preprocessor definitions, and a single assembly that works with native libraries compiled for multiple OSes.
Here's an example of what you have to do in .net right now to p/invoke ogg_packet, defined here:
[StructLayout(LayoutKind.Sequential)]structOggPacket{IntPtrPacket;
#if WINDOWS// long is always 4 bytes on WindowsintBytes;intBeginningOfStream;intEndOfStream;
#else // long matches the word length on Linux/OSXIntPtrBytes;IntPtrBeginningOfStream;IntPtrEndOfStream;
#endif
longGranulePosition;longPacketNumber;}
Ugly, and I need to ship separate binaries for Windows and OSX/Linux.
To be clear, this is partly about word length and partly about what "long" means in compiled C code on Windows (vs basically every other OS):
Thinking some more about implementation, it might make the most sense to just go with something like [MarshalAs(UnmanagedType.CLong)] applied to a regular Int32 (or UInt32), like so:
@EgorBo That refers to types that vary in size by word length (32-bit, 64-bit etc.). Different request but easy to confuse (I originally used the term "native long" but changed it to try and avoid this confusion).
....so why isn't the native code considered "buggy", in that it's using a type with a variable size definition? Especially since the next set of fields has an explicit size?
(Frankly, this is one of my least favorite C/C++ "features", for mostly this reason - that, and in almost all cases the far more interesting information is the range of the domain type, not the size of the physical type)
The merits of using long isn’t really the point.. my example is a pre-existing API already present on most Linux distributions. And it isn’t particularly obscure - I can provide other examples.
This isn't sufficient. This would not allow the upper 32-bits to be used on 64-bit Linux.
Likewise, using long could cause a loss of data on Windows, if managed code were to set the upper 32-bits.
If this were to be handled, it would likely need to be done by an explicit type that the runtime will dynamically size as needed (much like IntPtr or Vector<T>)
I suppose that’s potentially true, although in many (most?) cases the upper 32 bits are not particularly useful (considering that the code is assumed to work on platforms with 4 byte longs). I’m curious if there is any new code being written with longs. My assumption is that their occurance in code is a legacy holdover from when 64-bit architectures were a pipe dream.
Totally not against a “CLong” type, just playing this through. Any solution would be super helpful.
I would like to hope that most "modern/new" C/C++ code is being written to be cross-platform and cross-architecture aware and that they will use explicitly sized types (int32_t, int64_t, intptr_t, etc), rather than relying on the C/C++ language keywords (int, long, long long, etc). And looking around at various "newer" codebases that are explicitly meant to be cross-platform/architecture, they tend to do this (clang, llvm, vulkan, among others).
In an ideal world, many of these codebases (such as Ogg) would have been updated to use intptr_t instead of long when 64-bit computers first started coming out (and the difference between Unix and other platforms was realized). This would have ensured that both Unix and other platforms (such as Windows) had consistently sized structures. But that didn't happen, and left us with the current mess. Due to the differences in size, and common existence for older code-bases, I think its something that still needs some sort of answer, and having a specially recognized type that is the appropriate size on each platform seems like the best solution. This ensures that you have no potential for data loss (when dealt with properly) and gives you a single entry-point for the function interop, rather than needing to cross-compile everything.
[MarshalAs(UnmanagedType.CLong] int EndOfStream;
This isn't sufficient. This would not allow the upper 32-bits to be used on 64-bit Linux.
I think [MarshalAs(UnmanagedType.CLong] on int or long would be sufficient. It would work just like any other interop marshaling and throw exceptions when the data does not fit.
If this were to be handled, it would likely need to be done by an explicit type that the runtime will dynamically size as needed
I do not think a special casing like this would be worth it in this case.
It would work just like any other interop marshaling and throw exceptions when the data does not fit.
Which requires you to actually marshal the data, rather than allowing pinning or blitting of the value on 64-bit. If you expect to support 64-bit, you have to use long (or intptr), because you can't necessarily guarantee that the input (from either side) is always less than 32-bits on non-Windows. This also means that Windows is less efficient/etc.
We could potentially just handle this at the framework level, with #ifdef and a Unix vs Windows specific implementation (much like we do for IntPtr).
What kind of performance overhead are we talking about? Just the overhead of copying arrays of these things vs pinning, or would even my example be affected somewhat? I’d be reluctant to implement anything that slowed my solution down noticeably. Would probably stick with cross compiling in performance critical code if that is the case.
You example would get some extra instructions as well, in some cases at least.
MarshalAs(UnmanagedType.CLong) would have similar performance characteristics and limitations as passing bool over managed/unmanaged boundary. C# bool has to be converted to C++ bool, similar to how C# int or long has to be converted to C++ long here.
I think the best argument for not introducing a new type is that this issue relates to legacy / awkward code interop only. first-class support seems like overkill.
On the other hand, if adding the type isn’t too hard, the performance advantages might be nice. And it’s probably cleaner.
I will leave it up to you experts. both solutions are acceptable and I’d just like to see something as soon as possible!
Just want to make sure the attribute would deal with sign extension.
I think the best argument for not introducing a new type is that this issue relates to legacy / awkward code interop only
+1
adding the type isn’t too hard, the performance advantages might be nice. And it’s probably cleaner.
Adding a first class type for this is complex. Many different parts of the system would have to know about it, depending on how much first class this type would be. I do not think it is cleaner from the architecture point of view at least. The interop specific constructs should stay within the interop subsystem.
Once #12375 is fixed, there would be no changes needed in the IL stubs to support a "treat a struct as if it was a primitive for ABI reasons" type flag or attribute.
We can start small and just introduce the CLong types, without the general attribute. It sounds reasonable to me.
I think that is also reasonable. But, I think the attribute is a bit more generally useable and it is likely to more widely used than just CLong/CULong.
The immediately obvious and "required" scenario is indeed for CLong/CULong since we can't very well easily define a new primitive type (and we probably don't want to either, seeing as it's really for interop).
The more general use-case is to provide a general mechanism for the same in the future so that we don't need to go modifying the IL again. For example, the iOS/macOS environment also has nfloat which is float on 32-bit and double on 64-bit.
However, outside of a few scenarios (iWatch is one, iirc), Apple has largely dropped support for 32-bit so it isn't strictly needed and the scenarios where you have to support it as 32-bits will decrease over time (unlike CLong which applies to 64-bit and is a general C primitive that keeps getting used).
But, such an attribute would allow Xamarin to provide a type which is handled correctly without us needing to support it directly in the S.P.Corelib.
Likewise, it would be useable outside the strictly "required" scenario for things like HRESULT or other handles/typedefs where devs frequently define a wrapper type. WPF is one example and is why we need special handling for COM that ignores the correct ABI, such an attribute would allow us to make a "breaking change" where they can trivially attribute their types and maintain the same behavior.
I think it would be fine to add nfloat along the same lines CLong. It needs to be bitness-specific anyway. We have number of number of Windows-specific core interop types, so having one Apple-specific core interop type would be reasonable .
The "not strictly required" scenarios can be handled by source generators. I would wait for where the source generators will bring us and then we check again whether the general attribute understood by the runtime is needed.
we still generate significantly different codegen for returning int vs returning a HRESULT struct.
I am not sure which part you mean. The only int vs. HRESULT inefficiency that I can see in your snippet is unnecessary RBP frame for HRESULT in CreateDXGIFactory3.
I'm also not quite sure why we are saving all the non-volatile registers when they aren't live, which seems a separate issue
This is required for PInvoke transition (digressing from what this issue about).
Likewise, it would be useable outside the strictly "required" scenario for things like HRESULT or other handles/typedefs where devs frequently define a wrapper type. WPF is one example and is why we need special handling for COM that ignores the correct ABI, such an attribute would allow us to make a "breaking change" where they can trivially attribute their types and maintain the same behavior.
Unfortunately it wasn't just WPF. This had external uses as well. I don't think we can ever fix that decision. However, if we could fix that decision by adopting the attribute I would be, after you, its biggest champion.
I think it would be fine to add nfloat along the same lines CLong. It needs to be bitness-specific anyway
Do you have a concern with implementing CLong/CULong (and possibly NFloat) using an internal TransparentStructAttribute, rather than hardcoding those types explicitly? It seems like its the more straightforward approach and allows one path to support both types.
I would like the special handling for these to not require marshaling stub, ie tell the JIT directly what to do when it matters; do not create a new type of marshaler for this. I do not think that the internal TransparentStructAttribute would help you much with doing it this way. I would just check for the types by name in MethodTableBuilder::CheckForSystemTypes.
Do you have a concern with implementing CLong/CULong (and possibly NFloat) using an internal TransparentStructAttribute, rather than hardcoding those types explicitly?
I personally just don't like the idea of a public attribute modifying a struct in this way. It seems like a mechanism that is going can be abused and then we wind up owning the semantics - similar to the struct HRESULT issue above.
However, starting out with a private attribute as an implementation detail of this feature with the option to make it public later is something I could get behind.
tell the JIT directly what to do when it matters; do not create a new type of marshaler for this.
I am reading @tannergooding's suggestion as wanting the trigger to be the TransparentStructAttribute name instead of any in the set { CLong, CULong, NFloat }. I agree we shouldn't have a new marshaler.
Right, my suggestion wasn't to add a new marshaler but was instead to keep TransparentStructAttribute as the "marker" for this support and to make it internal only for the time being.
Activity
jherby2k commentedon Oct 3, 2018
Thinking some more about implementation, it might make the most sense to just go with something like [MarshalAs(UnmanagedType.CLong)] applied to a regular Int32 (or UInt32), like so:
EgorBo commentedon Oct 3, 2018
Looks like what you need is proposed here https://github.com/dotnet/corefxlab/blob/master/docs/specs/nativesized.md
jherby2k commentedon Oct 3, 2018
@EgorBo That refers to types that vary in size by word length (32-bit, 64-bit etc.). Different request but easy to confuse (I originally used the term "native long" but changed it to try and avoid this confusion).
Clockwork-Muse commentedon Oct 3, 2018
....so why isn't the native code considered "buggy", in that it's using a type with a variable size definition? Especially since the next set of fields has an explicit size?
(Frankly, this is one of my least favorite C/C++ "features", for mostly this reason - that, and in almost all cases the far more interesting information is the range of the domain type, not the size of the physical type)
jherby2k commentedon Oct 3, 2018
tannergooding commentedon Oct 4, 2018
[MarshalAs(UnmanagedType.CLong] int EndOfStream;This isn't sufficient. This would not allow the upper 32-bits to be used on 64-bit Linux.
Likewise, using
longcould cause a loss of data on Windows, if managed code were to set the upper 32-bits.If this were to be handled, it would likely need to be done by an explicit type that the runtime will dynamically size as needed (much like
IntPtrorVector<T>)jherby2k commentedon Oct 4, 2018
I suppose that’s potentially true, although in many (most?) cases the upper 32 bits are not particularly useful (considering that the code is assumed to work on platforms with 4 byte longs). I’m curious if there is any new code being written with longs. My assumption is that their occurance in code is a legacy holdover from when 64-bit architectures were a pipe dream.
Totally not against a “CLong” type, just playing this through. Any solution would be super helpful.
tannergooding commentedon Oct 4, 2018
I would like to hope that most "modern/new" C/C++ code is being written to be cross-platform and cross-architecture aware and that they will use explicitly sized types (int32_t, int64_t, intptr_t, etc), rather than relying on the C/C++ language keywords (int, long, long long, etc). And looking around at various "newer" codebases that are explicitly meant to be cross-platform/architecture, they tend to do this (clang, llvm, vulkan, among others).
In an ideal world, many of these codebases (such as Ogg) would have been updated to use
intptr_tinstead oflongwhen 64-bit computers first started coming out (and the difference between Unix and other platforms was realized). This would have ensured that both Unix and other platforms (such as Windows) had consistently sized structures. But that didn't happen, and left us with the current mess. Due to the differences in size, and common existence for older code-bases, I think its something that still needs some sort of answer, and having a specially recognized type that is the appropriate size on each platform seems like the best solution. This ensures that you have no potential for data loss (when dealt with properly) and gives you a single entry-point for the function interop, rather than needing to cross-compile everything.jkotas commentedon Oct 4, 2018
I think
[MarshalAs(UnmanagedType.CLong]onintorlongwould be sufficient. It would work just like any other interop marshaling and throw exceptions when the data does not fit.I do not think a special casing like this would be worth it in this case.
tannergooding commentedon Oct 4, 2018
This keeps coming up (the most notable likely being from @migueldeicaza: https://github.com/dotnet/coreclr/issues/963), and the only "correct" solution, today, is to cross-compile.
Which requires you to actually marshal the data, rather than allowing pinning or blitting of the value on 64-bit. If you expect to support 64-bit, you have to use long (or
intptr), because you can't necessarily guarantee that the input (from either side) is always less than 32-bits on non-Windows. This also means that Windows is less efficient/etc.We could potentially just handle this at the framework level, with
#ifdefand a Unix vs Windows specific implementation (much like we do forIntPtr).jkotas commentedon Oct 4, 2018
dotnet/coreclr#963 is a different issue from this one. I think that paying the price to marshal the data is perfectly fine for CLong.
jherby2k commentedon Oct 4, 2018
jkotas commentedon Oct 4, 2018
You example would get some extra instructions as well, in some cases at least.
MarshalAs(UnmanagedType.CLong)would have similar performance characteristics and limitations as passingboolover managed/unmanaged boundary. C#boolhas to be converted to C++bool, similar to how C#intorlonghas to be converted to C++longhere.jherby2k commentedon Oct 4, 2018
I think the best argument for not introducing a new type is that this issue relates to legacy / awkward code interop only. first-class support seems like overkill.
On the other hand, if adding the type isn’t too hard, the performance advantages might be nice. And it’s probably cleaner.
I will leave it up to you experts. both solutions are acceptable and I’d just like to see something as soon as possible!
Just want to make sure the attribute would deal with sign extension.
jkotas commentedon Oct 4, 2018
+1
Adding a first class type for this is complex. Many different parts of the system would have to know about it, depending on how much first class this type would be. I do not think it is cleaner from the architecture point of view at least. The interop specific constructs should stay within the interop subsystem.
34 remaining items
jkotas commentedon Apr 22, 2020
It is where it is today, but it is not pretty and we keep finding new bugs in it. Related: #12375 and #33129
jkoritzinsky commentedon Apr 22, 2020
Once #12375 is fixed, there would be no changes needed in the IL stubs to support a "treat a struct as if it was a primitive for ABI reasons" type flag or attribute.
tannergooding commentedon Apr 22, 2020
I think that is also reasonable. But, I think the attribute is a bit more generally useable and it is likely to more widely used than just
CLong/CULong.The immediately obvious and "required" scenario is indeed for
CLong/CULongsince we can't very well easily define a new primitive type (and we probably don't want to either, seeing as it's really for interop).The more general use-case is to provide a general mechanism for the same in the future so that we don't need to go modifying the IL again. For example, the iOS/macOS environment also has
nfloatwhich isfloaton 32-bit anddoubleon 64-bit.However, outside of a few scenarios (iWatch is one, iirc), Apple has largely dropped support for 32-bit so it isn't strictly needed and the scenarios where you have to support it as 32-bits will decrease over time (unlike
CLongwhich applies to 64-bit and is a general C primitive that keeps getting used).But, such an attribute would allow Xamarin to provide a type which is handled correctly without us needing to support it directly in the S.P.Corelib.
Likewise, it would be useable outside the strictly "required" scenario for things like
HRESULTor other handles/typedefs where devs frequently define a wrapper type. WPF is one example and is why we need special handling for COM that ignores the correct ABI, such an attribute would allow us to make a "breaking change" where they can trivially attribute their types and maintain the same behavior.Its also worth noting that we still generate significantly different codegen for returning
intvs returning aHRESULTstruct. It looks like we don't quite optimize the former cleanly (likely just part of the first class struct work): https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABABgAJiBGAOgCUBXAOwwEt8YaBhCfAB1YAbGFADKIgG6swMXAG4AsACgylWoxbtOASRYiIfcVCkz5y5cQDM5WNgAmEJoICe5XBigMwGcgAk6AKKiAKoAMgAq5ADeyuRxlNb+QWHhABSsLOQS2IIMMACUsfExSvFl5ABqOXnkALxZ1TCKpfEAvkVxHQnkGT5VuTDR5ADmMBhy5O1KUxbW1EiUAEzkXNFdANoAIoKC2vzQGKkARJsAGgDi2kdo5AEsUM4AChC9tUdcthgwZ5cAYtjeaDOa63BAAjCiPgwHYZYZ1cgePI3R6wXCSGCiVhw+qImA3cQYUJ4DABKBQaDwgBmOTR+QAul0+FBWNkvmoFjAEF8oEwepkAPofGDYL4/bT/QEPKipfLNMobACyYwAFhA7Hs+IJUkqMKr1fxBAB5PhsRy4GgAOQgukEGVh9MZzNZg3mfJ8gs+3wu4vBQMWMrqAD4EcryQB3chMBg7OXxDbbXb7KCHE7ekF3DxPF4sN5CkVev6+h7psHeSHQ21MbEIzx48go2TozHV3H4sZE9yk8lQKk0goMlpxJks/Ps8ic7m8pIhCLkD3C0XeiUYIGWGWxzqD8jrHV6jVa3dq/fG01Mc1Wm12qsOrfD51j6cpOd5xeFyXOFAB2rB3XhyPRwQN3ILorAfQIZ0iF8Cx9d9pUKLcSnKeJiAAdkjGAI0fCJUnnfMxWXIE4NlLopnlLdQNdLDIM9fCi2cf14LKRCkMoNCmAwvxwJSHCoNo98GOIrdSLjci5ioBYqJWGilzotdGOKLoylQ59pLfFcHjkoDhM3JSxIkrjZ14mT30/eS4mYpDlNw18YPUj91xI5QpiAA==jkotas commentedon Apr 22, 2020
I think it would be fine to add nfloat along the same lines CLong. It needs to be bitness-specific anyway. We have number of number of Windows-specific core interop types, so having one Apple-specific core interop type would be reasonable .
The "not strictly required" scenarios can be handled by source generators. I would wait for where the source generators will bring us and then we check again whether the general attribute understood by the runtime is needed.
I am not sure which part you mean. The only int vs. HRESULT inefficiency that I can see in your snippet is unnecessary RBP frame for HRESULT in CreateDXGIFactory3.
This is required for PInvoke transition (digressing from what this issue about).
AaronRobinsonMSFT commentedon Apr 22, 2020
Unfortunately it wasn't just WPF. This had external uses as well. I don't think we can ever fix that decision. However, if we could fix that decision by adopting the attribute I would be, after you, its biggest champion.
tannergooding commentedon Apr 22, 2020
Do you have a concern with implementing
CLong/CULong(and possiblyNFloat) using an internalTransparentStructAttribute, rather than hardcoding those types explicitly? It seems like its the more straightforward approach and allows one path to support both types.jkotas commentedon Apr 22, 2020
I would like the special handling for these to not require marshaling stub, ie tell the JIT directly what to do when it matters; do not create a new type of marshaler for this. I do not think that the internal
TransparentStructAttributewould help you much with doing it this way. I would just check for the types by name inMethodTableBuilder::CheckForSystemTypes.AaronRobinsonMSFT commentedon Apr 22, 2020
I personally just don't like the idea of a public attribute modifying a struct in this way. It seems like a mechanism that is going can be abused and then we wind up owning the semantics - similar to the struct HRESULT issue above.
However, starting out with a private attribute as an implementation detail of this feature with the option to make it public later is something I could get behind.
AaronRobinsonMSFT commentedon Apr 22, 2020
I am reading @tannergooding's suggestion as wanting the trigger to be the
TransparentStructAttributename instead of any in the set {CLong,CULong,NFloat}. I agree we shouldn't have a new marshaler.tannergooding commentedon Apr 22, 2020
Right, my suggestion wasn't to add a new marshaler but was instead to keep
TransparentStructAttributeas the "marker" for this support and to make itinternalonly for the time being.AaronRobinsonMSFT commentedon Apr 22, 2020
@tannergooding I personally am okay with it being internal. I think @jkotas's point is that:
isn't much different than:
Regardless of how it is done, this conversation has convinced me it has value. I look forward to the PR 😉
jkotas commentedon Apr 22, 2020
The (internal) attributes are not free to lookup. It is cheaper to just check the name if the number of affected types is small.
AaronRobinsonMSFT commentedon Jul 6, 2020
I think @tannergooding capture this conversation very well and has folded all the feedback into #13788.
Closing as duplicate.