将字节数组转换为 Short 数组而不复制数据
我有一个字节数组,它们实际上是来自声卡的 16 位样本。所以1000字节实际上代表500个Short(16位值)。
目前我正在像这样转换它们:
byte [] inputData = new byte[1000];
short [] convertedData = new short[500];
Buffer.BlockCopy(inputData, 0, convertedData , 0, 1000);
它工作正常并且速度非常快,因为它是低级字节副本。
但是有没有办法在没有副本的情况下做到这一点?即告诉 C# 将这个内存区域视为 500 个 Shorts 的数组而不是 1000 个字节?我知道在 C/C++ 中我可以直接转换指针,它就可以工作。
此副本发生在一个紧密的循环中,每秒最多 5000 次,因此如果我可以删除该副本,那将是值得的。
I have an array of bytes that are actually 16-bit samples from a sound card. So 1000 bytes actually represents 500 Short (16-bit values).
Currently I'm converting them like this:
byte [] inputData = new byte[1000];
short [] convertedData = new short[500];
Buffer.BlockCopy(inputData, 0, convertedData , 0, 1000);
It works fine and it's pretty quick as it's a low-level byte copy.
However is there a way to do it without the copy? i.e. tell C# to treat this area of memory as an array of 500 shorts instead of 1000 bytes? I know that in C/C++ I could just cast the pointer and it would work.
This copy happens in a tight loop, up to 5000 times a second, so if I can remove the copy it would be worthwhile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
StructLayout
允许您控制类或结构中数据字段的物理布局。它通常在与需要特定布局的数据的非托管代码交互时使用。尝试一下:
StructLayout
lets you control the physical layout of the data fields in a class or structure. It is typically used when interfacing with unmanaged code which expects the data in a specific layout.Give this a try:
也许是 C 语言
的 C# 模拟 union
就可以解决问题。Perhaps a C# analog of the C-language
union
would do the trick.类似的事情,我没有检查,但也许这会对你有所帮助:)
something like that, i didnt check, but maybe that'll help you out :)