contributed by <Weinux
>
sysprog2017
w5
matrix
Weinux
先來看 matrix.h 檔案 :
row col 以及 *priv
等資料封裝在 Matrix 中, 把矩陣運算要有的方法 (e.g., assign equl mul) 將這些方法的 function pointer 封裝在 MatrixAlgo.
typedef struct {
int row, col;
void *priv;
} Matrix;
typedef struct {
void (*assign)(Matrix *thiz, Mat4x4);
bool (*equal)(const Matrix *l, const Matrix *r);
bool (*mul)(Matrix *dst, const Matrix *l, const Matrix *r);
} MatrixAlgo;
如果未來針對其中的方法有不同的實作, 僅需要講指標指到其他的實作就可以更改實作, 而且可以將實作與介面分開.
在 matrix_naive.c 中: 建立了 NaiveMatrixProvider 透過 designated initializer 把 asign equal mul
的指標指向目前 Naive 版本的實作
MatrixAlgo NaiveMatrixProvider = {
.assign = assign,
.equal = equal,
.mul = mul,
};
matrix_providers[]
未來實作 AVX SSE 版本時, 只需要在陣列中加入其他的 provider 就可以在 main 切換不同實作一開始的版本
#include "matrix.h"
#include <stdio.h>
MatrixAlgo *matrix_providers[] = {
&NaiveMatrixProvider,
};
int main()
{
MatrixAlgo *algo = matrix_providers[0];
未來可能的版本
#include "matrix.h"
#include <stdio.h>
MatrixAlgo *matrix_providers[] = {
&NaiveMatrixProvider,
&AvxMatrixProvider,
&SseMatrixProvider
};
int main()
{
MatrixAlgo *algo = matrix_providers[0]; // naive version
algo = matrix_providers[1]; // avx version
algo = matrix_providers[2]; // sse version