C#类型类中的额外字节? [英] C# Extra byte in type classes?

查看:53
本文介绍了C#类型类中的额外字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个更好的理解我写的代码的最新进展。我遇到了一些我认为我理解但却没有按预期工作的东西。很难解释所以让我先显示代码..

展开 | 选择 | Wrap | 行号

解决方案

好吧,我真的不知道为什么要么,但我认为它不会起作用。托管结构不能像无人管理(c ++)结构一样工作。这些字节只是折叠在结构的顶部并且填入中

我想如果你可以摆弄[StructLayout]并打包你可以使它工作的东西


也不完全确定,但是Byte是无符号的并且Int16是有符号的,因此16位的最左边是为符号保留的,这意味着它不是真正的两个8位值。 [1000 0000 0000 0000 = -32768不是+32768]并且MaxValue是[0111 1111 1111 1111:0x7FFF而不是0xFFFF]


那说,我无法解释为什么小数70会使任何差异。


尽管如此,理论上它可能会起作用,如果你使用了无符号的UInt16,但这不符合CLR,所以我想知道这是否也不会引起互操作问题。

感谢输入!我已经尝试使用无符号短裤,但它给出了相同的结果。我忘记了StructLayout属性,所以我玩了一会儿(在这里找到了一个更好的资源: VSJ |文章|掌握C#中的结构


但仍然无法通过..观察如何包装工作使我确信这是问题所在。这就是我提出的:

展开 | 选择 | Wrap | 行号


I''m looking for a better understanding of whats going on with the code i write. I have come across something that I thought I understood but its not working as expected. Its hard to explain so let me show the code first..

Expand|Select|Wrap|Line Numbers

解决方案

Well I don''t really know the "why" either, but I had figured it would not work. Managed Structs don''t work the way unmanged (c++) structs worked. Where the bytes were just folded on top of the struct and "filled it in"
I think if you maybe fiddle with the [StructLayout] and packing stuff you can make it work


Not completely sure either, but Byte is unsigned and Int16 is signed, so the leftmost of the 16 bits is reserved for the sign, meaning it is not truly two 8 bit values. [1000 0000 0000 0000 = -32768 not +32768] and the MaxValue is [0111 1111 1111 1111 : 0x7FFF not 0xFFFF]

That said, I cannot explain why the decimal 70 would make any difference.

Nonetheless, theoretically it might work if you used UInt16, unsigned, but that is not CLR compliant and so I wonder if that would not also cause interop problems.


thanks for the input! I had already tried using unsigned shorts but it gave the same results. I forgot about the StructLayout attribute, so i played around with it for a little bit (found a greate resource here: VSJ | Articles | Mastering structs in C#)

But still was not able to get it through..seeing how the packing worked made me think for sure that was the problem. This is what I came up with:

Expand|Select|Wrap|Line Numbers


这篇关于C#类型类中的额外字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆