Skip to content

Feature Request: Variable-size "long" for simplified p/invoke #27530

Closed

Description

@jherby2k

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:

C code:

typedef struct {
  unsigned char *packet;
  long  bytes;
  long  b_o_s;
  long  e_o_s;
  ogg_int64_t  granulepos;
  ogg_int64_t  packetno;
} ogg_packet;

C# code:

[StructLayout(LayoutKind.Sequential)]
struct OggPacket
{
    IntPtr Packet;
#if WINDOWS             // long is always 4 bytes on Windows
    int Bytes;
    int BeginningOfStream;
    int EndOfStream;
#else                   // long matches the word length on Linux/OSX
    IntPtr Bytes;
    IntPtr BeginningOfStream;
    IntPtr EndOfStream;
#endif
    long GranulePosition;
    long PacketNumber;
}

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):

Type Windows 32-bit Windows 64-bit *nix 32-bit *nix 64-bit
C# IntPtr 4 8 4 8
C# int (Int32) 4 4 4 4
C# long (Int64) 8 8 8 8
C long (no managed equivalent) 4 4 4 8

https://software.intel.com/en-us/articles/size-of-long-integer-type-on-different-architecture-and-os/

I get that this is technically up to the compiler, not the OS, but I believe the dust has settled on these sizes since the shift from 16->32->64 bits.

Activity

  1. jherby2k commented on Oct 3, 2018

    @jherby2k
    Author

    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:

    [StructLayout(LayoutKind.Sequential)]
    struct OggPacket
    {
        IntPtr Packet;
        [MarshalAs(UnmanagedType.CLong] int Bytes;
        [MarshalAs(UnmanagedType.CLong] int BeginningOfStream;
        [MarshalAs(UnmanagedType.CLong] int EndOfStream;
        long GranulePosition;
        long PacketNumber;
    }
  2. EgorBo commented on Oct 3, 2018

    @EgorBo
    Member
  3. jherby2k commented on Oct 3, 2018

    @jherby2k
    Author

    @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).

  4. Clockwork-Muse commented on Oct 3, 2018

    @Clockwork-Muse
    Contributor

    ....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)

  5. jherby2k commented on Oct 3, 2018

    @jherby2k
    Author
  6. tannergooding commented on Oct 4, 2018

    @tannergooding
    Member

    [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 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>)

  7. jherby2k commented on Oct 4, 2018

    @jherby2k
    Author

    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.

  8. tannergooding commented on Oct 4, 2018

    @tannergooding
    Member

    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.

  9. jkotas commented on Oct 4, 2018

    @jkotas
    Member

    [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.

  10. tannergooding commented on Oct 4, 2018

    @tannergooding
    Member

    I do not think a special casing like this would be worth it in this case.

    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.

    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).

  11. jkotas commented on Oct 4, 2018

    @jkotas
    Member

    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.

  12. jherby2k commented on Oct 4, 2018

    @jherby2k
    Author
  13. jkotas commented on Oct 4, 2018

    @jkotas
    Member

    would even my example be affected somewhat?

    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.

  14. jherby2k commented on Oct 4, 2018

    @jherby2k
    Author

    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.

  15. jkotas commented on Oct 4, 2018

    @jkotas
    Member

    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.

  16. 34 remaining items

  17. jkotas commented on Apr 22, 2020

    @jkotas
    Member

    the decision for COM and DllImport is currently made in ILMarshaler::EmitMarshalReturnValue

    It is where it is today, but it is not pretty and we keep finding new bugs in it. Related: #12375 and #33129

  18. jkoritzinsky commented on Apr 22, 2020

    @jkoritzinsky
    Member

    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.

  19. tannergooding commented on Apr 22, 2020

    @tannergooding
    Member

    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.

    Its also worth noting that we still generate significantly different codegen for returning int vs returning a HRESULT struct. 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==

    • 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
  20. jkotas commented on Apr 22, 2020

    @jkotas
    Member

    nfloat

    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).

  21. AaronRobinsonMSFT commented on Apr 22, 2020

    @AaronRobinsonMSFT
    Member

    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.

  22. tannergooding commented on Apr 22, 2020

    @tannergooding
    Member

    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.

  23. jkotas commented on Apr 22, 2020

    @jkotas
    Member

    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.

  24. AaronRobinsonMSFT commented on Apr 22, 2020

    @AaronRobinsonMSFT
    Member

    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.

  25. AaronRobinsonMSFT commented on Apr 22, 2020

    @AaronRobinsonMSFT
    Member

    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.

  26. tannergooding commented on Apr 22, 2020

    @tannergooding
    Member

    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.

  27. AaronRobinsonMSFT commented on Apr 22, 2020

    @AaronRobinsonMSFT
    Member

    @tannergooding I personally am okay with it being internal. I think @jkotas's point is that:

    else if (x || y || z) { ... }

    isn't much different than:

    else if (a) { ... }

    Regardless of how it is done, this conversation has convinced me it has value. I look forward to the PR 😉

  28. jkotas commented on Apr 22, 2020

    @jkotas
    Member

    The (internal) attributes are not free to lookup. It is cheaper to just check the name if the number of affected types is small.

  29. AaronRobinsonMSFT commented on Jul 6, 2020

    @AaronRobinsonMSFT
    Member

    I think @tannergooding capture this conversation very well and has folded all the feedback into #13788.

    Closing as duplicate.

  30. ghost locked as resolved and limited conversation to collaborators on Dec 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime.InteropServices

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions