Rust: Bindgen綁定CTP C++原生接口嘗試

1、 環境準備:linux

WSL2 +Bindgen + CTP C++ 接口 for linux
Bindgen: https://github.com/rust-lang/rust-bindgen

CTP for linux
在這裏插入圖片描述說明一下,我在windows環境下,一樣的方法,一直報libclang沒有找到,至今也沒有解決,看了github bindgen issues上提的問題,相似的問題很多。試了很多方法,終於放棄,轉WSL2.
git

2、構建wrapper.hpp 文件github

wrapper.hpp是告訴bindgen,我這些都須要幫我翻譯一下。東西在這呢。這個文件能夠放在src目錄下。windows

#include "../ctp_sdk/ThostFtdcMdApi.h"
#include "../ctp_sdk/ThostFtdcTraderApi.h"
#include "../ctp_sdk/ThostFtdcUserApiStruct.h"
#include "../ctp_sdk/ThostFtdcUserApiDataType.h"

3、倒騰build.rs文件
build.rs文件,放在工程目錄的根目錄下,我這兒的工程名是「rust_new_test」,build.rs放在和Cargo.toml同一目錄級下,並列就好。
app

use std::env;
use std::path::PathBuf;

fn main() { 
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("src/wrapper.hpp")
        /* // Tell cargo to invalidate the built crate whenever any of the // included header files changed. .parse_callbacks(Box::new(bindgen::CargoCallbacks)) */
        .ignore_methods()
        .rustified_enum(".*")
        .blacklist_item("CTP_SIDE_TYPE")
        .blacklist_item("CTP_POSITION_EFFECT_TYPE")
        .blacklist_item("TCTPTradeTypeType")
        .blacklist_item("TCTPOrderTypeType")
        .blacklist_function("TraderSpiStub_Rust.*")
        .blacklist_function("QuoteSpiStub_Rust.*")
        /* .default_enum_style(bindgen::EnumVariation::Rust { non_exhaustive: true, }) */
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    //let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let out_path = PathBuf::from("/home/sg/rust_new_test");
    println!("out_path: {:?}",out_path);
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}

blacklist_item、blacklist_function是指哪些不須要進行翻譯的項。ui

4、Cargo.tomlspa

[package]
name = "rust_new_test"
version = "0.1.0"
authors = ["sg"]
edition = "2018"

[dependencies]

lazy_static ="1.4"
libc = "0.2"

[build-dependencies]
bindgen = "0.55.1"
cc = "1.0"

5、lib.rs :視狀況翻譯

若是Cargo.toml文件中沒有lib設置(以下,相似),則lib.rs能夠忽略。code

[lib]
name ="ctp"
path ="src\lib.rs"

若是有lib設置,lib.rs路徑能夠設「src\lib.rs」,即放在src目錄下,設一個空文件便可。blog

6、cargo build
輸入:

cargo build

這樣,binding.rs就自動生成了。

相關文章
相關標籤/搜索