数値→ローマ数字へ

概要

数値からローマ数字への変換してみましょう。
簡単なところからHm.CppInvokeの雰囲気になれていきましょう。

数値→ローマ数字へ

  • C++側のソース

    ToRoman.dllとしてコンパイル
    #include <windows.h>
    #include <string>
    #include <vector>
    
    #include "HmCppInvoke.h"
    
    using namespace std;
    using namespace Hidemaru;
    
    // 数値をローマ数字にする
    std::wstring to_roman(int value) {
        vector<pair<int, wstring>> const roman_map_data{
          { 1000, L"M" },{ 900, L"CM" },
          { 500, L"D" },{ 400, L"CD" },
          { 100, L"C" },{ 90, L"XC" },
          { 50, L"L" },{ 40, L"XL" },
          { 10, L"X" },{ 9, L"IX" },
          { 5, L"V" },{ 4, L"IV" },
          { 1, L"I" }
        };
    
        wstring result;
        for (auto const& [num, str] : roman_map_data) {
            while (value >= num) {
                result += str;
                value -= num;
            }
        }
    
        return result;
    }
    
    
    extern "C" __declspec(dllexport) THmNumber test() {
        Hm.funcDllExport();
    
        try {
            // 数値を入力してください。input関数。
            auto ret = Hm.Macro.doFunction(L"input", L"数値入れてください");
    
            // 関数実行自体に何か不具合がありそう
            auto err = ret.getException();
            if (err.has_value()) {
                throw err.value();
            }
    
            // 文字列としてinputの内容を取得。失敗したらcatch節に飛ぶ
            wstring result = ret.getResult<wstring>();
    
            // 数値に変換してみる。失敗したらcatch節に飛ぶ
            int value = std::stoi(result);
    
            wstring roman_num = to_roman(value);
    
            Hm.OutputPane.output(L"変換結果:" + roman_num + L"\r\n");
        }
        catch (exception& e) {
            // エラー内容をchar → wstring へ
            auto wide_what = Text::Encoding::cp932_to_utf16( e.what() );
            Hm.OutputPane.output(wide_what + L"\r\n");
        }
    
    
        return 1;
    }
    
  • 秀丸マクロ側のソース

    test.mac
    // ToRoman.dllとしてコンパイルした
    #dll = loaddll(currentmacrodirectory + @"\ToRoman.dll");
     
    // 途中でマクロの文法や型の致命的エラーが発生した場合でもdllを解放する。
    if (version >= 898) { eval "keepdll #dll, 0"; }
     
    #r = dllfuncw(#dll, "test");
     
    freedll(#dll);