gpt4 book ai didi

c# - 将 C++ 例程转换为 C#,主要是指针

转载 作者:行者123 更新时间:2023-11-28 03:05:05 25 4
gpt4 key购买 nike

我主要是一名 C++ 程序员,但在业余时间我会尝试加快 C# 的速度。我有以下要转换的 C++ 函数-

#define COMPUTE_CRC32(cp,crc) (crc32lookup_table[((unsigned long)crc^(unsigned char)cp)&0xff]^(((unsigned long)crc>>8)&0x00FFFFFF))

unsigned long ComputeCRC32::Update(const void* ptrBytes, long numBytes)
{
const unsigned char* ptr_data = (const unsigned char*) ptrBytes;

while ( --numBytes >= 0 )
{
unsigned char data_byte = *ptr_data++ ;

m_ulCRC = COMPUTE_CRC32( data_byte, m_ulCRC );
}

return m_ulCRC;
}

我知道有很多方法可以做到这一点,但我想看看最好的方法是什么。这是我到目前为止创建的 -

public uint Update(object ptrBytes, int numBytes)
{
byte * ptr_data = (byte) ptrBytes;

while (--numBytes >= 0)
{
byte data_byte = *ptr_data++;

m_ulCRC = (GlobalMembersComputeCRC32.crc32lookup_table[((uint)m_ulCRC ^ (byte)data_byte) & 0xff] ^ (((uint)m_ulCRC >> 8) & 0x00FFFFFF));
}

return m_ulCRC;
}

转换指针的最佳方法是什么?有没有更好的方法用 C# 重写它?

最佳答案

C# 是一种具有指针的语言,但也具有引用(和 references are not necessarily addresses )。 C# 中的 byte[] 等数组是表示您可能在 C++ 中使用指针的内容的常用方法。

要使用指针,请使用 unsafe .如果您考虑使用 C#,人们往往会避免使用 unsafe,因为它通常是“不安全的”;相反,运行时会强制执行检查以避免诸如数组中的缓冲区溢出之类的事情。相反,Crc32 的伪代码可能是:

public uint Crc32(byte[] data) {
uint result;
for (int i= 0; i < data.Length; i++) {
byte data_byte = data[i];
result = doCrc(...stuff with data_byte...);
}
return result;
}

请注意,for 循环使用 data.Length 作为其限制检查(引用:Eric Gunnerson: Efficiency of iteration over arrays),因为这可以通过 JIT 针对数组长度进行优化.如果您使用单独的长度参数,则不能,因此应避免这种情况(或与长度结合使用,如果所需的迭代次数可能小于数组长度)。

关于c# - 将 C++ 例程转换为 C#,主要是指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com