Windowsでc++がRustライブラリを呼び出す例


前述したように、本稿の例は64ビットの例であり、32ビットの例は他の人のドキュメントを参考にして、文章の末尾に示すことができる.
環境準備
  • インストールmingw、私のインストールmingw 64、ディレクトリ:D:/tools/mingw 64/
  • rustをインストールするには、デフォルトのインストールを選択しないでください.
  • Current installation options:
    
    
       default host triple: x86_64-pc-windows-msvc
         default toolchain: stable
                   profile: default
      modify PATH variable: yes
    
    1) Proceed with installation (default)
    2) Customize installation
    3) Cancel installation
    >2
    
    I'm going to ask you the value of each of these installation options.
    You may simply press the Enter key to leave unchanged.
    
    Default host triple?
    x86_64-pc-windows-gnu
    
    Default toolchain? (stable/beta/nightly/none)
    stable
    
    Profile (which tools and data to install)? (minimal/default/complete)
    default
    
    Modify PATH variable? (y/n)
    y
    
  • はC:Usersxxxx.cargoディレクトリの下にconfigファイルを新規作成し、
  • と書きます.
    [build]
    target="x86_64-pc-windows-gnu"
    

    rustライブラリ
    プロジェクトの作成:
    cargo new mylib --lib
    

    カーゴでtomlに追加:
    [dependencies]
    libc = "*"  
    
    [lib]
    crate-type = ["staticlib"] #   
    
    #    :    panic    ,       
    [profile.release]
    panic="abort"  
    
    #    :    panic    ,       
    [profile.dev]
    panic="abort"
    

    rustソースを追加するには:
    //src/lib.rs
    extern crate libc;
    use libc::uint32_t;
    
    #[no_mangle]
    pub extern "C" fn addition(a: uint32_t, b: uint32_t) -> uint32_t {
        a + b
    }
    

    コンパイル:debugバージョン:
    cargo build
    

    releaseバージョンの場合は、次のようになります.
    cargo build --release
    

    cppファイル
    ソース:
    //   :caller.cpp
    #include 
    #include 
    
    extern "C" {
         uint32_t
         addition(uint32_t, uint32_t);
    }
    
    int main(void) {
        uint32_t sum = addition(1, 2);
        printf("%u
    ", sum); return 0; }

    コンパイル:
    x86_64-w64-mingw32-g++ -c -o win_cpp_caller.o caller.cpp
    

    コンパイル生成exe
    D:/tools/mingw64/bin/x86_64-w64-mingw32-g++ -static win_cpp_caller.o -o win_cpp_caller -L./mylib/target/x86_64-pc-windows-gnu/debug -lmylib  -ladvapi32 -lws2_32 -luserenv
    

    win_の生成に成功しましたcpp_caller.exeファイル
    まとめ
    本明細書の例は64ビットの例を示し、32ビットの例はドキュメントを参照することができる.https://medium.com/csis-techblog/cross-compiling-and-statically-linking-against-rust-libraries-2c02ee2c01afしかし、この例もCargoにあるはずです.tomlにpanic=「abort」を追加します.ここの主なピットはpanic=「abort」を追加する必要があるはずです.
    もちろん、ネット上ではmsvcを使ってコンパイルする例もありますが、面倒なようで、意外にも穴があるかもしれません.