📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

 
(同じ利用者による、間の10版が非表示)
9行目: 9行目:
<br>
<br>
Qtには組み込みのTOMLパーサーが存在しないため、サードパーティ製ライブラリを使用する必要がある。<br>
Qtには組み込みのTOMLパーサーが存在しないため、サードパーティ製ライブラリを使用する必要がある。<br>
一般的に、<u>toml11ライブラリ</u>や<u>toml++ライブラリ</u>等のサードパーティ製ライブラリがよく使用されている。<br>
一般的に、<u>toml++ライブラリ</u>や<u>toml11ライブラリ</u>等のサードパーティ製ライブラリがよく使用されている。<br>
<br>
これらのライブラリを使用することにより、TOMLファイルの読み込み、書き込み、データの解析が容易になる。<br>
これらのライブラリを使用することにより、TOMLファイルの読み込み、書き込み、データの解析が容易になる。<br>
<br>
<br>
60行目: 61行目:
*: 例:
*: 例:
*: <syntaxhighlight lang="toml">
*: <syntaxhighlight lang="toml">
  [database]
[database]
  server = "192.168.1.1"
server = "192.168.1.1"
  ports = [ 8001, 8001, 8002 ]
ports = [ 8001, 8001, 8002 ]
  </syntaxhighlight>
</syntaxhighlight>
*: <br>
*: <br>
* インラインテーブル
* インラインテーブル
73行目: 74行目:
*: 例:
*: 例:
*: <syntaxhighlight lang="toml">
*: <syntaxhighlight lang="toml">
  [[fruits]]
[[fruits]]
  name = "apple"
name = "apple"
 
  [[fruits]]
[[fruits]]
  name = "banana"
name = "banana"
  </syntaxhighlight>
</syntaxhighlight>
*: <br>
*: <br>
* コメント
* コメント
*: シャープ記号 (<code>#</code>) を使用する。
*: シャープ記号 (<code>#</code>) を使用する。
<br><br>
== TOMLファイルの例 ==
<syntaxhighlight lang="toml">
# config.tomlファイル
title = "設定ファイル"  # トップレベルのキー
[user]                # ユーザ情報のセクション
name = "山田太郎"
age = 30
email = "yamada@example.com"
[application]        # アプリケーション設定のセクション
version = "1.0.0"
debug_mode = false
[database]            # データベース接続情報のセクション
host = "localhost"
port = 5432
username = "admin"
password = "secret"
[features]            # 機能のオン / オフを制御するセクション
enabled = ["login", "logout", "dashboard"]
disabled = ["admin_panel"]
[logging]            # ロギング設定のセクション
level = "info"
file = "/var/log/app.log"
[[servers]]          # サーバ情報の配列
ip = "192.168.1.1"
role = "frontend"
[[servers]]          # サーバ情報の配列
ip = "192.168.1.2"
role = "backend"
</syntaxhighlight>
<br><br>
<br><br>


220行目: 260行目:
  )
  )
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br>
 
==== 同期処理 ====
== 同期処理 ==
===== TOMLの読み込み =====
==== TOMLの読み込み ====
以下の例では、toml++ライブラリを使用して、TOMLファイルを読み込んでいる。<br>
以下の例では、toml++ライブラリを使用して、TOMLファイルを読み込んでいる。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
293行目: 332行目:
  </syntaxhighlight>
  </syntaxhighlight>
<br>
<br>
==== TOMLファイルの書き込み ====
===== TOMLファイルの書き込み =====
以下の例では、toml++ライブラリを使用して、TOMLファイルを書き込んでいる。<br>
以下の例では、toml++ライブラリを使用して、TOMLファイルを書き込んでいる。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
389行目: 428行目:
  }
  }
  </syntaxhighlight>
  </syntaxhighlight>
<br>
==== 非同期処理 ====
===== TOMLの読み込み =====
以下の例では、toml++ライブラリを使用して、非同期でTOMLファイルを読み込んでいる。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
<br>
<syntaxhighlight lang="c++">
// AsyncTomlHandler.hファイル
#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QBuffer>
#include <QFuture>
#include <QtConcurrent>
#include <stdexcept>
#include <toml++/toml.h>
class AsyncTomlHandler : public QObject
{
    Q_OBJECT
private:
    toml::table readTomlFromDevice(QIODevice* device)
    {
      std::unique_ptr<QIODevice> devicePtr(device); // デバイスの自動クリーンアップを保証
      return readTomlStream(device);
    }
 
public:
    explicit AsyncTomlHandler(QObject *parent = nullptr) : QObject(parent) {}
    // TOMLファイルを非同期で読み込む
    QFuture<toml::table> readTomlAsync(const QString& filename)
    {
      return QtConcurrent::run([this, filename]() {
          return this->readTomlFromDevice(new QFile(filename));
      });
    }
    // TOMLデータをストリームから読み込む
    toml::table readTomlStream(QIODevice* device)
    {
      if (!device->open(QIODevice::ReadOnly | QIODevice::Text)) {
          throw std::runtime_error("デバイスを開けません");
      }
      QTextStream in(device);
      QString content = in.readAll();
      device->close();
      try {
          return toml::parse(content.toStdString());
      }
      catch (const toml::parse_error &err) {
          throw std::runtime_error(QString("TOMLデータの解析エラー: %1").arg(err.description().c_str()).toStdString());
      }
    }
    // メモリ上のTOMLデータを読み込む
    toml::table readTomlFromMemory(const QByteArray& data)
    {
      QBuffer buffer;
      buffer.setData(data);
      return readTomlStream(&buffer);
    }
};
</syntaxhighlight>
<br>
以下の例では、上記のクラスを使用してTOMLファイルを非同期で読み込んでいる。<br>
<br>
<syntaxhighlight lang="c++">
#include <QCoreApplication>
#include <QFuture>
#include <QFutureWatcher>
#include <QDebug>
#include "AsyncTomlHandler.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    AsyncTomlHandler handler;
    // 非同期でTOMLファイルを読み込む
    QFuture<toml::table> readFuture = handler.readTomlAsync("config.toml");
    QFutureWatcher<toml::table> readWatcher;
    QObject::connect(&readWatcher, &QFutureWatcher<toml::table>::finished, [&]() {
      try {
          toml::table data = readWatcher.result();
          qDebug() << "Name:" << QString::fromStdString(data["name"].value_or(""));
          qDebug() << "Age:" << data["age"].value_or(0);
      }
      catch (const std::exception &e) {
          qCritical() << "エラー: " << e.what();
          QCoreApplication::quit();
      }
    });
    readWatcher.setFuture(readFuture);
    return a.exec();
}
</syntaxhighlight>
<br>
===== TOMLファイルの書き込み =====
以下の例では、toml++ライブラリを使用して、非同期でTOMLファイルを書き込んでいる。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
<br>
<syntaxhighlight lang="c++">
// AsyncTomlHandler.hファイル
#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QBuffer>
#include <QFuture>
#include <QtConcurrent>
#include <stdexcept>
#include <toml++/toml.h>
class AsyncTomlHandler : public QObject
{
    Q_OBJECT
private:
    toml::table readTomlFromDevice(QIODevice *device)
    {
      std::unique_ptr<QIODevice> devicePtr(device); // デバイスの自動クリーンアップを保証
      return readTomlStream(device);
    }
    void writeTomlToDevice(QIODevice *device, const toml::table &data)
    {
      std::unique_ptr<QIODevice> devicePtr(device); // デバイスの自動クリーンアップを保証
      writeTomlStream(device, data);
    }
public:
    explicit AsyncTomlHandler(QObject *parent = nullptr) : QObject(parent) {}
    // TOMLファイルを非同期で読み込む
    QFuture<toml::table> readTomlAsync(const QString &filename)
    {
      return QtConcurrent::run([this, filename]() {
          return this->readTomlFromDevice(new QFile(filename));
      });
    }
    // TOMLデータを非同期でファイルに書き込む
    QFuture<void> writeTomlAsync(const QString &filename, const toml::table &data)
    {
      return QtConcurrent::run([this, filename, data]() {
          this->writeTomlToDevice(new QFile(filename), data);
      });
    }
    // TOMLデータをストリームから読み込む
    toml::table readTomlStream(QIODevice *device)
    {
      if (!device->open(QIODevice::ReadOnly | QIODevice::Text)) {
          throw std::runtime_error("デバイスを開けません");
      }
      QTextStream in(device);
      QString content = in.readAll();
      device->close();
      try {
          return toml::parse(content.toStdString());
      }
      catch (const toml::parse_error &err) {
          throw std::runtime_error(QString("TOMLデータの解析エラー: %1").arg(err.description().c_str()).toStdString());
      }
    }
    // TOMLデータをストリームに書き込む
    void writeTomlStream(QIODevice *device, const toml::table &data)
    {
      if (!device->open(QIODevice::WriteOnly | QIODevice::Text)) {
          throw std::runtime_error("デバイスを開けません");
      }
      QTextStream out(device);
      out << QString::fromStdString(toml::toml_formatter(data).format());
      device->close();
    }
    // メモリ上のTOMLデータを読み込む
    toml::table readTomlFromMemory(const QByteArray &data)
    {
      QBuffer buffer;
      buffer.setData(data);
      return readTomlStream(&buffer);
    }
    // メモリ上にTOMLデータを書き込む
    QByteArray writeTomlToMemory(const toml::table &data)
    {
      QBuffer buffer;
      writeTomlStream(&buffer, data);
      return buffer.buffer();
    }
};
</syntaxhighlight>
<br>
以下の例では、上記のクラスを使用して、非同期でTOMLファイルを書き込んでいる。<br>
<br>
<syntaxhighlight lang="c++">
#include <QCoreApplication>
#include <QFuture>
#include <QFutureWatcher>
#include <QDebug>
#include "AsyncTomlHandler.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    AsyncTomlHandler handler;
    // 非同期でTOMLファイルを読み込む
    QFuture<toml::table> readFuture = handler.readTomlAsync("config.toml");
    QFutureWatcher<toml::table> readWatcher;
    QObject::connect(&readWatcher, &QFutureWatcher<toml::table>::finished, [&]() {
      try {
          toml::table data = readWatcher.result();
          qDebug() << "Name:" << QString::fromStdString(data["name"].value_or(""));
          qDebug() << "Age:" << data["age"].value_or(0);
          // データを変更
          data["location"] = "Tokyo";
          // 非同期で変更したデータを書き込む
          QFuture<void> writeFuture = handler.writeTomlAsync("config_updated.toml", data);
          QFutureWatcher<void> writeWatcher;
          QObject::connect(&writeWatcher, &QFutureWatcher<void>::finished, []() {
            qDebug() << "書き込み完了";
            QCoreApplication::quit();
          });
          writeWatcher.setFuture(writeFuture);
      }
      catch (const std::exception &e) {
          qCritical() << "エラー:" << e.what();
          QCoreApplication::quit();
      }
    });
    readWatcher.setFuture(readFuture);
    return a.exec();
}
</syntaxhighlight>
<br>
===== TOMLファイルの書き込み : メモリ操作 (ストリーミング処理) =====
以下の例では、toml++ライブラリを使用して、メモリ上のTOMLデータを書き込んでいる。<br>
toml++ライブラリを使用する場合は、プロジェクトにtoml++ライブラリをリンクする必要がある。<br>
<br>
# メモリ上のTOMLデータを読み込む。
# 読み込んだデータを表示して、一部のデータを変更する。
# 変更したデータをメモリに書き込み、結果を表示する。
<br>
<syntaxhighlight lang="c++">
#include <QCoreApplication>
#include <QDebug>
#include "AsyncTomlHandler.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    AsyncTomlHandler handler;
    // メモリ上のTOMLデータを定義
    QByteArray tomlData = R"(
      title = "TOMLサンプル"
      [owner]
      name = "山田太郎"
      age = 30
      [database]
      enabled = true
      ports = [ 8000, 8001, 8002 ]
      data = [ ["delta", "phi"], [3.14] ]
      temp_targets = { cpu = 79.5, case = 72.0 }
    )";
    try {
      // メモリからTOMLデータを読み込む
      toml::table data = handler.readTomlFromMemory(tomlData);
      // 読み込んだデータを表示
      qDebug() << "メモリから読み込んだTOMLデータ:";
      qDebug() << "タイトル:" << QString::fromStdString(data["title"].value_or(""));
      qDebug() << "オーナー名:" << QString::fromStdString(data["owner"]["name"].value_or(""));
      qDebug() << "オーナー年齢:" << data["owner"]["age"].value_or(0);
      qDebug() << "データベース有効:" << data["database"]["enabled"].value_or(false);
      // データを変更
      data["owner"]["location"] = "東京";
      data["database"]["version"] = "1.0.0";
      // 変更したデータをメモリに書き込む
      QByteArray updatedData = handler.writeTomlToMemory(data);
      // 更新されたデータを表示
      qDebug() << "更新されたTOMLデータ:";
      qDebug() << updatedData;
      // 更新されたデータを再度読み込んで確認
      toml::table updatedTable = handler.readTomlFromMemory(updatedData);
      qDebug() << "更新後のデータ確認:";
      qDebug() << "オーナー所在地:" << QString::fromStdString(updatedTable["owner"]["location"].value_or(""));
      qDebug() << "データベースバージョン:" << QString::fromStdString(updatedTable["database"]["version"].value_or(""));
    }
    catch (const std::exception &e) {
      qCritical() << "エラー: " << e.what();
    }
    QCoreApplication::quit();
    return a.exec();
}
</syntaxhighlight>
<br><br>
== toml11ライブラリ ==
==== toml11ライブラリとは ====
toml11は、C++でTOML (Tom's Obvious, Minimal Language) ファイルを解析および生成するためのヘッダオンリーのライブラリである。<br>
このライブラリは、C++11以降の標準に準拠しており、使いやすさと効率性を重視して設計されている。<br>
<br>
toml11ライブラリの主な特徴として、高い性能と柔軟性が挙げられる。<br>
TOMLパーサーは再帰下降法を用いて実装されており、エラー報告機能も備えている。<br>
これにより、TOMLファイルの解析中に問題が発生した場合、具体的なエラー情報を得ることができる。<br>
<br>
このライブラリは、TOMLの様々なデータ型をサポートしている。<br>
例えば、文字列、整数、浮動小数点数、真偽値、日付時刻、配列、テーブル等を扱うことができる。<br>
また、ユーザ定義型への変換機能も提供しており、カスタムデータ構造との連携が容易である。<br>
<br>
toml11ライブラリの使用方法は比較的簡単である。<br>
ヘッダファイルをインクルードして、<code>parse</code>メソッドを使用することにより、TOMLファイルを読み込むことができる。<br>
解析されたデータは、C++の標準コンテナに似た方法でアクセスできる。<br>
<br>
また、toml11ライブラリはTOMLデータの生成もサポートしており、<br>
C++のオブジェクトからTOML形式の文字列を作成することが可能であり、これによりTOMLファイルの出力も簡単に行うことができる。<br>
<br>
toml11ライブラリは、依存関係が無く、ヘッダファイルのみで実装されているため、プロジェクトへの導入が容易である。<br>
<br>
このライブラリは、設定ファイルの処理やアプリケーション間でのデータ交換等、様々なシナリオで活用できる強力なツールとなっている。<br>
<br>
==== toml11ライブラリのライセンス ====
toml11ライブラリのライセンスはMITライセンスに準拠しているため、商用プロジェクトを含む幅広い用途で自由に使用することができる。<br>
<br>
==== toml++ライブラリのインストール ====
===== パッケージ管理システムからインストール =====
# RHEL
sudo dnf install toml11-devel
# SUSE
-
<br>
===== ソースコードからインストール =====
[https://github.com/ToruNiina/toml11 toml11ライブラリのGithub]にアクセスして、ソースコードをダウンロードする。<br>
ダウンロードしたファイルを解凍する。<br>
tar xf toml11-<バージョン>.tar.gz
cd toml11-<バージョン>
<br>
toml11ライブラリをビルドおよびインストールする。<br>
mkdir build && cd build
# CMakeコマンドを使用する場合
cmake -DCMAKE_BUILD_TYPE=Release          \
      -DCMAKE_INSTALL_PREFIX=<toml11ライブラリのインストールディレクトリ> \
      -DTOML11_PRECOMPILE=ON              \  # スタティックライブラリをインストールする場合
      ..
make -j $(nproc)
make install
<br>
==== 同期処理 ====
===== TOMLの読み込み =====
<br>
===== TOMLファイルの書き込み =====
<br>
==== 非同期処理 ====
===== TOMLの読み込み =====
<br>
===== TOMLファイルの書き込み =====
<br><br>
<br><br>


{{#seo:
|title={{PAGENAME}} : Exploring Electronics and SUSE Linux | MochiuWiki
|keywords=MochiuWiki,Mochiu,Wiki,Mochiu Wiki,Electric Circuit,Electric,pcb,Mathematics,AVR,TI,STMicro,AVR,ATmega,MSP430,STM,Arduino,Xilinx,FPGA,Verilog,HDL,PinePhone,Pine Phone,Raspberry,Raspberry Pi,C,C++,C#,Qt,Qml,MFC,Shell,Bash,Zsh,Fish,SUSE,SLE,Suse Enterprise,Suse Linux,openSUSE,open SUSE,Leap,Linux,uCLnux,Podman,電気回路,電子回路,基板,プリント基板
|description={{PAGENAME}} - 電子回路とSUSE Linuxに関する情報 | This page is {{PAGENAME}} in our wiki about electronic circuits and SUSE Linux
|image=/resources/assets/MochiuLogo_Single_Blue.png
}}


__FORCETOC__
__FORCETOC__
[[カテゴリ:Qt]]
[[カテゴリ:Qt]]