将现有的 API 与新的 类 连接起来

Interfacing an existing API with new classes

考虑为 c# 包装 opengl 的 OpenTK 库。它带有 API 希望您使用的内置矩阵 classes。比如这个方法中的重载。

    public static void UniformMatrix4(int location, bool transpose, ref Matrix4 matrix);
    public static void UniformMatrix4(int location, bool transpose, ref Matrix4d matrix);
    public static void UniformMatrix4(int location, int count, bool transpose, double* value);
    public static void UniformMatrix4(int location, int count, bool transpose, double[] value);
    public static void UniformMatrix4(int location, int count, bool transpose, float* value);
    public static void UniformMatrix4(int location, int count, bool transpose, float[] value);
    public static void UniformMatrix4(int location, int count, bool transpose, ref double value);
    public static void UniformMatrix4(int location, int count, bool transpose, ref float value);

所有 API 都遵循相同的形式。作为使用内置矩阵 class 的替代方法,我可以使用浮点指针或浮点数组等。

现在,我不想使用 OpenTK 的矩阵 class 或他们的任何其他数学结构,但我确实想使用他们的 API。我有什么选择可以将我自己的 Matrix class 连接到 api,既干净又高效。

我的矩阵 class 的内部存储不使用 float[] 而是使用 float 字段。我不认为有一种方法可以提取浮点数组以传递给 API 而不会低效地将字段复制到新数组中。

在 C# 中使用低级指针操作存在不安全的可能性(参见 details),因此您可以获得第一个 float 元素的地址,并将其传递给 OpenTK 的函数。

我认为,如果您可以重新实现自己的 Matrix class。

,您可以使用 "fixed arrays"(参见 link)