6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nimとrustでmessagebox(windows)

Last updated at Posted at 2018-08-21

(18/08/22 7:36 加筆、修正しました)

この記事は、ここに書いてあることの抜粋です

https://github.com/khchen/winim ← nim
https://wesleywiser.github.io/post/rust-windows-messagebox-hello-world/ ← rust
著作権とか大丈夫だろうか...

nim

コードです

msgbox.nim
proc MessageBoxA*(hWnd: int, lpText: cstring, 
                  lpCaption: cstring, uType: int32): int32 
                 {.discardable, stdcall, dynlib: "user32", importc.}
        
MessageBoxA(0, "Hello, world !", "MessageBox Example", 0)

コンパイル、実行

nim c -r msgbox

また、WinAPIをいろいろ使えるようにした、winimというものがあるようです。これが、上記のリンク先にあるものです。
はじめに、winimを入れます。

With git on windows:

nimble install winim

gitなしの場合は、上記のリンクにやり方があります。

コードです

msgbox2.nim
import winim/lean
MessageBox(0, "Hello, world !", "Nim is Powerful", 
           MB_OK or MB_ICONINFORMATION)

コンパイル、実行

nim c -r msgbox2

私はnimbleでやったのですが、コンパイルの際コマンドラインに--noBabelPathというオプションがついていて、うまくコンパイルできませんでした。なので、コマンドをコピペして、--noBabelPathだけ削除してコンパイルしました。

rust

詳しいことは、上記のリンクに書いてあります。google翻訳やると日本語になります。ここでは、簡単にやり方だけ書きます。

はじめにCargoを使用して新しいプロジェクトを作成します。

cargo new --bin hello_world

そして、この場合に作成されるhello_worldフォルダにあるCargo.tomlファイルを開き、[dependencies]と書かれている行を見つけ、その下に次を追加します。

winapi = "0.2.7"
user32-sys = "0.2.0"

そして、src/main.rsを開き、次のようにします。

src/main.rs
extern crate user32;
extern crate winapi;

use std::ffi::CString;
use user32::MessageBoxA;
use winapi::winuser::{MB_OK, MB_ICONINFORMATION};

fn main() {
    let lp_text = CString::new("Hello, world!").unwrap();
    let lp_caption = CString::new("MessageBox Example").unwrap();

    unsafe {
        MessageBoxA(
            std::ptr::null_mut(),
            lp_text.as_ptr(),
            lp_caption.as_ptr(),
            MB_OK | MB_ICONINFORMATION
        );
    }
}

コンパイル、実行

cargo build
cargo run

また、このAPIのUnicode版を書きたい場合は、上記のリンクの違うページにあるようです。

環境

OS:
Microsoft Windows [Version 10.0.17134.228]

nim:
Nim Compiler Version 0.18.0 [Windows: amd64]
Copyright (c) 2006-2018 by Andreas Rumpf

nimble:
nimble v0.8.10 compiled at 2018-03-01 23:04:46
git hash: 6a2da5627c029460f6f714a44f5275762102fa4b

rustc:
rustc 1.24.1 (d3ae9a9e0 2018-02-27)

cargo:
cargo 0.25.0 (96d8071da 2018-02-26)

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?