# custom\_memory\_allocator

## custom\_memory\_allocator サンプル

### 概要

Diarkis C++ ランタイム内で行われるメモリの確保・開放処理をユーザーが実装したアロケータを使用するように変更することができます。 本サンプルではカスタムアロケータの実装と設定方法について紹介します。

### ローカル環境でサーバーを起動する

サンプルで使用するサーバーを起動するためのチュートリアルを実施して、ローカル環境で Diarkis サーバーを起動します。

[Diarkis サーバをローカルで起動する](/getting-started/tutorial/setup-local-server.md)

### サンプルの引数

サンプルの起動時には以下の３つのパラメータを指定してください。

| 引数         | 説明                            |
| ---------- | ----------------------------- |
| serverAddr | Diarkis サーバのエンドポイントを指定してください  |
| UID        | 接続するユーザーの ID を任意の文字列で指定してください |
| clientKey  | クライアントキーを任意の文字列で指定してください      |

#### 起動例：

`custom_memory_allocator.exe 192.168.1.123:7000 1111 AAAA`

### 起動方法

本サンプルは単体で実行することができ、起動すると指定された Diarkis サーバに接続し切断します。

### サンプルコード説明

カスタムアロケータの実装方法と設定方法に分けて紹介します。 また、本サンプルでは基礎的な Diarkis サーバへの接続方法等は説明していません。必要に応じて room\_broadcast 等の基礎的なサンプルを参照してください。

#### カスタムアロケータの実装方法

カスタムアロケータは `ICustomAllocator` を継承して実装します。

```
/**
* This is a sample implementation of the custom allocator.
* The user can implement their own custom allocator by inheriting Diarkis::ICustomAllocator.
*/
class SampleCustomAllocator : public Diarkis::ICustomAllocator
{
public:
    ...
```

`ICustomAllocator` には以下のインターフェイスが存在し、それらをアプリ側の都合に合わせて実装します。本サンプルでは単純に malloc/free でメモリの確保と開放を行っています。

```
void* Allocate(size_t size, int flag) override
{
    ...
    return ptr;
}

void* AlignedAllocate(size_t size, size_t align, int flag) override
{
    ...
    return ptr;
}

void  Deallocate(void* ptr) override
{
    ...
}
```

#### カスタムアロケータの設定方法

実装したカスタムアロケータのインスタンスを用意し、`SetCustomAllocator` で Diarkis C++ ランタイムへ設定します。異なるアロケータが混在して使用されないように必ずすべての Diarkis 関連の API 呼び出しよりも前に設定するようにしてください。

```
// Replace the default allocator of the Diarkis runtime with the custom allocator user implemented.
// You need to set the custom allocator before calling any Diarkis runtime functions.
Diarkis::SetCustomAllocator(&gCustomAllocator);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.diarkis.io/diarkis-client/samples/cpp/custom_memory_allocator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
