将"const float *"从 C++ 转换为 C#

translating "const float *" from C++ to C#

本文关键字:转换 C++ const float      更新时间:2023-10-16

如何将这C++代码片段转换为 C#?

void fm_getAABB(..., const float *points, ...)
{    
   // ...
   const unsigned char *source = (const unsigned char *) points;
   //...    
   const float *p = (const float *) source;
   //...
}

我已经尝试使用C++到 C# 转换器,但它似乎也无法翻译它。

编辑:
这是整个函数:

void fm_getAABB(unsigned int vcount, const float *points, unsigned int pstride,
    float *bmin, float *bmax)
{
    const unsigned char *source = (const unsigned char *) points;
    bmin[0] = points[0];
    bmin[1] = points[1];
    bmin[2] = points[2];
    bmax[0] = points[0];
    bmax[1] = points[1];
    bmax[2] = points[2];
    for (unsigned int i = 1; i < vcount; i++)
    {
        source+=pstride;
        const float *p = (const float *) source;
        if ( p[0] < bmin[0] ) bmin[0] = p[0];
        if ( p[1] < bmin[1] ) bmin[1] = p[1];
        if ( p[2] < bmin[2] ) bmin[2] = p[2];
        if ( p[0] > bmax[0] ) bmax[0] = p[0];
        if ( p[1] > bmax[1] ) bmax[1] = p[1];
        if ( p[2] > bmax[2] ) bmax[2] = p[2];
    }
}

一种选择是使用 C# 的不安全模式按原样转换此内容。C# 完全能够通过少量修改来运行此代码。例如,您需要删除 const 修饰符。

如果您设法生成仅托管版本,那当然会更好。但并不完全清楚这是否可能:您的函数正在执行某些指针操作,这可能会导致未对齐的访问。托管阵列无法使用仅托管功能以不对齐的方式进行 PE 访问。

在 C# 中使用指针没有安全的方法,C# 是一种比 C++ 更安全的语言,但这也会使它在这种情况下更具限制性。

C++将允许你做许多其他语言不能做的事情,因为它将安全留给了程序员,但是 C# 将安全放在首位,因此限制了这样的事情的发生。

如果不看到更多的上下文,很难说。我希望您将能够用浮点数组替换所有指针的使用。

通常,C++指针用于单个项目或项目数组,但我无法确定从您的示例代码中分辨出哪个 - 但复数"点"的使用似乎表明它是一个数组。

若要在字符(字节)数组和其他值之间进行转换,请使用 BitConverter 类。

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

这是 C# 对类型双关语的回答 const unsigned char *source = (const unsigned char *) points;

但它需要深入了解此函数的作用,并基本上以 C# 方式重新实现它。