Rust : CTP中交互中字符串及处理

从C端读到的假设是[c_char,16]类似结构,可以如下处理:

   let s_16 = String::from("abc").to_char_16() ;//假设从C端读到[i8;16]
    let s_16 :Vec<u8> = s_16.iter().map(|&x|x as u8).collect(); 
    let string_utf8_lossy = String::from_utf8_lossy(&s_16);
    println!("string_utf8_lossy: {} ,len:{}", string_utf8_lossy,string_utf8_lossy.len());
    let mut vec_of_u8 = vec![];
    vec_of_u8.extend_from_slice(&s_16);
    let string_utf8_result = String::from_utf8(vec_of_u8).unwrap();

    println!("string_utf8_result: {}", string_utf8_result);
    // [u8] to str (result)
    let str_utf8_result = str::from_utf8(&s_16).unwrap();
    println!("str_utf8_result: {}", str_utf8_result);
    let vec_of_chars: Vec<char> = s_16.iter().map(|byte| *byte as char).collect();
    println!("vec_of_chars: {:?}", vec_of_chars);

如果从c接口中返回的数据中格式如下:

    fn on_rtn_depth_marketdata(&mut self, pDepthMarketData: &MarketDataField) {
        let ctp_bytes_i8:[i8;81] = pDepthMarketData.InstrumentID;
        let ctp_bytes_u8_vec:Vec<u8> = pDepthMarketData.InstrumentID.iter().map(|&x|x as u8).collect();
        let untrim_instr = String::from_utf8_lossy(&ctp_bytes_u8_vec);
        println!("ctp传过来的i8数据:{:?}",ctp_bytes_i8);
        println!("ctp -> string:");
        println!("修剪前 string :{}, len :{}",untrim_instr,untrim_instr.len());
        let trim_instr = untrim_instr.trim_matches(char::from(0));
        println!("修剪后 string :{}, len : {}",trim_instr,trim_instr.len());
        println!("desk = >  instrument_id : {:?} \n",trim_instr);
        println!("desk = >  close         : {:?} \n",pDepthMarketData.ClosePrice);
        let md = MdSpiOnRtnDepthMarketData {
            depth_market_data: pDepthMarketData.clone(),
        };
    }

我们可以看到处理的结果:

ctp传过来的i8数据:[73, 70, 50, 49, 48, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ctp -> string:
修剪前 string :IF2103, len :81
修剪后 string :IF2103, len : 6
desk = >  instrument_id : "IF2103" 

desk = >  close         : 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0 

你可能感兴趣的:(Rust)