So I have a C API with the following struct
typedef struct mat4f_ { float m[4][4]; } mat4f;
It gets passed as a parameter to one of my API functions:
void myFunction(const mat4f matrix);
I am exporting this function to C# in Unity using a dll:
[DllImport ("mylib")]
private static extern void myFunction(mat4f matrix);
My question is, what should I make the corresponding C# struct be?
Right now I have the following:
[StructLayout(LayoutKind.Sequential)]
public struct mat4f
{
public float[,] m;
}
and use try to use the function as follows:
//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
Is this the correct thing to do? Is there a better way to do this?
We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure.
Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures. Nested Structures are allowed in C Programming Language.
A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows.
For a 4×4 matrix, you can use UnityEngine.Matrix4x4
. If you want to use your own struct, I recommend you implement it the same way UnityEngine.Matrix4x4
is implemented:
[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
};
}
This is a blittable type. Blittable types do not require conversion when they are passed between managed and unmanaged code.
Sample use:
mat4f matrix = mat4f.Identity;
myFunction(matrix); // Call DLL function
Existing implementations are similar to the one I presented above.
UnityEngine.Matrix4x4
docs.Vector4
type is also a value type.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With