# NativeBuffer开发指导 (C/C++)

#### 场景介绍

NativeBuffer模块提供**共享内存**功能，支持内存的申请、使用、查询和释放等操作。

NativeBuffer的常见开发场景：通过Native API申请OH\_NativeBuffer实例，获取内存属性，将ION内存映射到进程空间。

#### 接口说明

| 接口名 | 描述 |
| --- | --- |
| OH_NativeBuffer_Alloc (const OH_NativeBuffer_Config *config) | 通过OH_NativeBuffer_Config创建OH_NativeBuffer实例，每次调用都会产生一个新的OH_NativeBuffer实例。本接口需要与OH_NativeBuffer_Unreference接口配合使用，否则会存在内存泄露。 |
| OH_NativeBuffer_Reference (OH_NativeBuffer *buffer) | 将OH_NativeBuffer对象的引用计数增加1。 |
| OH_NativeBuffer_Unreference (OH_NativeBuffer *buffer) | 将OH_NativeBuffer对象的引用计数减1，当引用计数为0的时候，该NativeBuffer对象会被析构掉。 |
| OH_NativeBuffer_GetConfig (OH_NativeBuffer *buffer, OH_NativeBuffer_Config *config) | 用于获取OH_NativeBuffer的属性。 |
| OH_NativeBuffer_Map (OH_NativeBuffer *buffer, void **virAddr) | 将OH_NativeBuffer对应的ION内存映射到进程空间。 |
| OH_NativeBuffer_Unmap (OH_NativeBuffer *buffer) | 将OH_NativeBuffer对应的ION内存从进程空间移除。 |
| OH_NativeBuffer_GetSeqNum (OH_NativeBuffer *buffer) | 获取OH_NativeBuffer的序列号。 |

详细的接口说明请参考native\_buffer。

#### 开发步骤

以下步骤描述了如何使用NativeBuffer提供的Native API接口创建OH\_NativeBuffer实例，获取内存属性信息，并将ION内存映射到进程空间。

**添加动态链接库**

CMakeLists.txt中添加以下lib。

```
libnative_buffer.so
```

**头文件**

```
#include <native_buffer/native_buffer.h>
```

1.  **创建OH\_NativeBuffer实例**。
    
    ```
    OH_NativeBuffer_Config config {
        .width = 0x100,
        .height = 0x100,
        .format = NATIVEBUFFER_PIXEL_FMT_RGBA_8888,
        .usage = NATIVEBUFFER_USAGE_CPU_READ | NATIVEBUFFER_USAGE_CPU_WRITE | NATIVEBUFFER_USAGE_MEM_DMA,
    };
    
    OH_NativeBuffer *nativeBuffer = OH_NativeBuffer_Alloc(&config);
    if (nativeBuffer == nullptr) {
        LOGE("OH_NativeBuffer_Alloc fail, nativeBuffer is null");
    }
    ```
    
2.  **将OH\_NativeBuffer对应的ION内存映射到进程空间**。
    
    应用如需访问buffer内存空间，可通过OH\_NativeBuffer\_Map接口将ION内存映射到进程空间。
    
    ```
    void* virAddr = nullptr;
    int32_t ret = OH_NativeBuffer_Map(nativeBuffer, &virAddr);
    if (ret != 0) {
        LOGE("OH_NativeBuffer_Map Failed");
    }
    // ...
    ret = OH_NativeBuffer_Unmap(nativeBuffer);
    if (ret != 0) {
        LOGE("OH_NativeBuffer_Unmap Failed");
    }
    ```
    
3.  **获取内存的属性信息**。
    
    ```
    OH_NativeBuffer_Config config2 = {};
    OH_NativeBuffer_GetConfig(nativeBuffer, &config2);
    uint32_t hwBufferID = OH_NativeBuffer_GetSeqNum(nativeBuffer);
    ```
    
4.  **销毁OH\_NativeBuffer**。
    
    ```
    OH_NativeBuffer_Unreference(nativeBuffer);
    nativeBuffer = nullptr;
    ```