c# - 如何在 C# Unity 中使用带有二维数组的 C 结构

标签 c# c unity3d dll struct

所以我有一个具有以下结构的 C API

typedef struct mat4f_ { float m[4][4]; } mat4f;

它作为参数传递给我的一个 API 函数:

void myFunction(const mat4f matrix);

我正在使用 dll 将此函数导出到 Unity 中的 C#:

[DllImport ("mylib")] 
private static extern void myFunction(mat4f matrix);

我的问题是,我应该将相应的 C# 结构设为什么?

现在我有以下内容:

[StructLayout(LayoutKind.Sequential)]
public struct mat4f
{
    public float[,] m;
}

并尝试使用如下函数:

//Just make an identity matrix
mat4f matrix; 
matrix.m = new float[4, 4] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };

myFunction(matrix); //Call dll function

这是正确的做法吗?有一个更好的方法吗?

最佳答案

对于 4×4 矩阵,您可以使用 UnityEngine.Matrix4x4 .如果你想使用你自己的结构,我建议你用 UnityEngine.Matrix4x4 的实现方式来实现它:

[StructLayout(LayoutKind.Sequential)]
public struct mat4f
{
    public float m00;
    public float m01;
    public float m02;
    public float m03;
    public float m10;
    public float m11;
    public float m12;
    public float m13;
    public float m20;
    public float m21;
    public float m22;
    public float m23;
    public float m30;
    public float m31;
    public float m32;
    public float m33;

    public static mat4f Identity = new mat4f
    {
        m11 = 1.0f,
        m22 = 1.0f,
        m33 = 1.0f,
        m44 = 1.0f
    };
}

这是一个 blittable type . Blittable 类型在托管代码和非托管代码之间传递时不需要转换

示例使用:

mat4f matrix = mat4f.Identity;
myFunction(matrix);  // Call DLL function

现有的实现与我上面介绍的类似。

关于c# - 如何在 C# Unity 中使用带有二维数组的 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171779/

相关文章:

c# - 内存锁以确保共享数据可以被多个线程读取,但只能由一个线程写入?

c - 扫描名称和奇怪的字符串: Files

node.js - 在游戏中同步 NPC 行为。使用 socket.io/node.js。 Unity2D

使用递归计算紊乱? (c代码)

c - 递归strcpy函数

c# - 无法播放禁用的音频源(Unity 2d)

c# - 将 Prolog 与 C# (Unity) 结合使用

C# - 当方法参数验证失败时,我应该踢回异常吗?

c# - IObservable 与 NetMQ 接收

c# - 32 位快速统一哈希函数。使用 MD5/SHA1 并截掉 4 个字节?