---
title: calculate
description: "调用此函数对基础算子进行计算，目前支持密态矩阵加法、密态矩阵减法、密态矩阵乘法。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengcctrustzone/tee/kcal/kunpeng_kcal_16_0086.html
sourcePath: /source/zh/kunpengcctrustzone/tee/kcal/kunpeng_kcal_16_0086.html
indexId: dd20c68fcccb17453d57583b78db06293b0e43e65dc06c83a75904ada8772a5c64
---
# calculate

调用此函数对基础算子进行计算，目前支持密态矩阵加法、密态矩阵减法、密态矩阵乘法。

```
int calculate(
DG_TeeCtx *dgTeeCtx,
DG_AlgorithmsType type,
DG_MpcMatShareSet *shareSet,
DG_MpcMatShare **share
)
```

#### 参数

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| dgTeeCtx | KCAL上下文信息 | 为initTeeCtx成功初始化的结果 | 输入 |
| type | 算子枚举 DG\_AlgorithmsType | MATRIX\_ADD：矩阵加法 MATRIX\_SUB：矩阵减法 MATRIX\_MUL：矩阵乘法 | 输入 |
| shareSet | 分片数据组装后的结构体 类型为DG\_MpcMatShareSet | 不能输入为NULL | 输入 |
| share | 计算结果 类型为：DG\_MpcMatShare | 一级指针为NULL,二级指针不为NULL | 输出 |


**表1 DG_MpcMatShareSet结构体**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| \*shareSet | DG\_MpcMatShare | 每个参与方的分片 |
| size | unsigned long | 参与方数量 |


**表2 DG_MpcMatShare结构体**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| dataShare | Share\* | 分片结构 |
| row | unsigned long | 矩阵行数 |
| col | unsigned long | 矩阵列数 |
| shareType | DG\_ShareType | 分片类型 |


#### 返回值

- 成功：返回0。
- 失败：返回错误码。


#### 错误码

| 错误码 | 错误码值 | 描述 | 特殊说明 |
| --- | --- | --- | --- |
| DG\_ERR\_MPC\_TEE\_INVALID\_PARAM | 4501 | 无效参数 | \- |
| DG\_ERR\_MPC\_TEE\_INVALID\_ALGORITHM\_TYPE | 4502 | 无效算法类型 | \- |
| DG\_ERR\_MALLOC\_FAIL | 51 | 内存分配失败 | \- |
| DG\_ERR\_MPC\_TEE\_DIV\_IS\_ZERO | 4512 | 除0异常 | \- |
| DG\_FAILURE | 1 | 算子执行失败 | 参数校验失败 分片失败 接收对方数据失败 |


#### 依赖

- dgTeeCtx依赖  initTeeCtx
的成功初始化。
- 入参需要依赖调用makeShare后的结果作为入参。
- 依赖的头文件为"data_guard_mpc.h"。


#### 示例

```
#include  "data_guard_mpc.h"
//计算方
DG_AlgorithmsType type = MATRIX_MUL;
std::unique_ptr<DG_MpcMatShareSet> shares = std::make_unique<DG_MpcMatShareSet>();
std::unique_ptr<DG_MpcMatShare[]> share_datas = std::make_unique<DG_MpcMatShare[]>(2);
share_datas[0] = *share2;
share_datas[1] = *share1;
shares->shareSet = share_datas.get();
shares->row = 2;
shares->col = 2;
DG_MpcMatShare *share_out = nullptr;
res = aritOpts.calculate(dgTee, type, shares.get(), &share_out);
```

说明：计算的为矩阵乘法算子，样例只做参考，share1和share2为分片的结果，不能真正运行。

运行结果：shares不为NULL和res为0。

- 调用initTeeCtx成功后的dgTeeCtx来调用calculate接口。
- 通过分片获取的是单个数据方的分片结果，需要用户多次调用makeShare，将各方的数据DG_MpcMatShare拼接成DG_MpcMatShareSet，需要注意的是拼接的先后顺序，例如调用矩阵乘法算子，矩阵a乘以矩阵b（a为计算节点1的数据，b为计算节点0的数据），计算节点0获取到a的分片后，需要将a的分片放到DG_MpcMatShareSet的第0个位置，将b的分片放到第1个位置。
- 只支持2方运算，需设置一方为0节点，另一方为1节点。
