Skip to content

Instantly share code, notes, and snippets.

@sincerefly
Created September 12, 2017 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sincerefly/042e657885d103cb9c4e67fa0dc87eff to your computer and use it in GitHub Desktop.
Save sincerefly/042e657885d103cb9c4e67fa0dc87eff to your computer and use it in GitHub Desktop.
rust include_bytes宏示例,加载DLL到EXE中,使用时解压出来调用,调用DLL并将DLL返回的信息复制到粘贴板
extern crate clipboard;
use clipboard::ClipboardProvider;
use clipboard::ClipboardContext;
extern crate libloading;
use libloading::{Library, Symbol};
use std::io::prelude::*;
use std::path::Path;
use std::ffi::CStr;
use std::fs::File;
use std::str;
use std::io;
type GetHylinkDeviceId = unsafe fn() -> *const i8;
const LIBRARY_PATH: &'static str = "PcInfo.dll";
const HYLINK_DLL: &'static [u8] = include_bytes!("PcInfo.dll");
fn generate_hylink_dll(filename: &str, buf: &[u8]) -> io::Result<()> {
let mut f = try!(File::create(filename));
try!(f.write(&buf));
Ok(())
}
fn copy_to_clipboard(x3id: String) {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
println!("{:?}", ctx.get_contents());
ctx.set_contents(x3id).unwrap();
}
fn get_x3id() -> String {
// 如果不存在DLL文件,生成DLL
if !Path::new(LIBRARY_PATH).exists() {
match generate_hylink_dll(LIBRARY_PATH, HYLINK_DLL) {
Ok(s) => println!("Generate hylink dll file success {:?}", s),
Err(r) => println!("Generate hylink dll file failed {:?}", r),
}
}
// 从本地加载DLL文件
let lib = Library::new(LIBRARY_PATH).unwrap();
println!("{:?}", lib);
// 调用DLL获取标识码
let x3id = unsafe {
let func: Symbol<GetHylinkDeviceId> = lib.get(b"GetHylinkDeviceId").unwrap();
let c_buf: *const i8 = func();
let c_str: &CStr = CStr::from_ptr(c_buf);
let str_slice: &str = c_str.to_str().unwrap();
let str_buf: String = str_slice.to_owned();
str_buf
};
x3id
}
fn main() {
// 从DLL中获取X3标识码
let x3id: String = get_x3id();
println!("{:?}", x3id);
// 将标识码复制到粘贴板
copy_to_clipboard(x3id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment