• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

如何在Windows上制作一个包含.lib和.dll的Rust Crate包

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

最近看了下Rust,作为系统编程语言,真的是很复杂。我计划做一个简单的Rust模块,用于调用Dynamsoft Barcode Reader SDK,然后打包发布到https://crates.io/

制作发布Rust Crate包

创建Rust lib工程:

cargo new dbr --lib

lib.rs中添加:

pub mod reader;

reader模块对应reader.rs文件,所以需要创建reader.h, reader.c

// reader.h
typedef struct Barcode {
    char* barcode_type;
    char* barcode_value;
} Barcode;

typedef __int32 int32_t;
typedef void (*RustCallback)(int32_t, const char *, const char *);

int32_t register_callback(RustCallback callback);
void c_decodeFile(const char *fileName, const char *pszLicense);
// reader.c
#include "reader.h"
#include "DynamsoftBarcodeReader.h"
#include <stdio.h>

RustCallback cb;

int32_t register_callback(RustCallback callback) {
    cb = callback;
    return 1;
}

void c_decodeFile(const char *fileName, const char *pszLicense)
{
    void *hBarcode = DBR_CreateInstance();

    if (hBarcode)
    {
        int ret = DBR_InitLicense(hBarcode, pszLicense);
        STextResultArray *paryResult = NULL;
        ret = DBR_DecodeFile(hBarcode, fileName, "");
        DBR_GetAllTextResults(hBarcode, &paryResult);
        int count = paryResult->nResultsCount;
        printf("Barcode found: %d\n", count);
        int i = 0;
        for (; i < count; i++)
        {
            // printf("Index: %d, Barcode Type: %s, Value: %s\n", i, paryResult->ppResults[i]->pszBarcodeFormatString, paryResult->ppResults[i]->pszBarcodeText);
            if (cb) 
            {
                cb(i, paryResult->ppResults[i]->pszBarcodeFormatString, paryResult->ppResults[i]->pszBarcodeText);
            }
        }
        DBR_FreeTextResults(&paryResult);
        DBR_DestroyInstance(hBarcode);
    }
}

接下来用bindgenreader.h转换成reader.rs

cargo install bindgen
bindgen src/reader.h -o src/reader.rs

在根目录创建build.rs用于构建工程。在构建的时候把.lib和.dll文件都拷贝到输出目录,然后把输出目录设置成库的查找路径:

extern crate cc;
extern crate bindgen;

use std::env;
use std::fs;
use std::path::Path;

fn main() {
    
    // Get the output path
    let out_dir = env::var("OUT_DIR").unwrap();
    let package_offset = out_dir.find("package").unwrap_or(0);

    if package_offset == 0 {
        // Generates Rust FFI bindings.
        let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("src/reader.h")
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

        bindings
            .write_to_file("src/reader.rs")
            .expect("Couldn't write bindings!");
    }

    // Build C code.
    cc::Build::new()
        .include("include")
        .file("src/reader.c")
        .compile("reader");

    // Copy *.dll & .lib to the output path
    let dll_src: String = String::from("./platforms/win/DynamsoftBarcodeReaderx64.dll");
    let dll_dest_path = Path::new(&out_dir).join("DynamsoftBarcodeReaderx64.dll");
    let _dll_result = fs::copy(dll_src, dll_dest_path);

    let lib_src: String = String::from("./platforms/win/DBRx64.lib");
    let lib_dest_path = Path::new(&out_dir).join("DBRx64.lib");
    let _lib_result = fs::copy(lib_src, lib_dest_path);

    // Link Dynamsoft Barcode Reader.
    // println!("cargo:rustc-link-search={}", env!("DBR_LIB"));
    println!("cargo:rustc-link-search={}", &out_dir);
    println!("cargo:rustc-link-lib=DBRx64");
}

上面的代码除了库的链接,还包括C代码的编译以及.h文件到.rs文件的转换。

Cargo.toml中添加依赖

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

生成reader.rs:

cargo build

在打包前,记得把文件类型添加到Cargo.toml中:

include = [
    "**/*.lib",
    "**/*.dll",
    "**/*.rs",
    "**/*.c",
    "**/*.h",
    "Cargo.toml",
]

[lib]
name = "dbr"
path = "src/lib.rs"

Crate打包:

cargo package

https://crates.io/me生成token,通过命令行登录:

cargo login <token>

发布Crate包:

cargo publish

这里是我制作的dbr包:https://crates.io/crates/dbr

使用方法

创建一个新的Rust工程:

cargo new test

Cargo.toml中添加依赖:

[dependencies]
dbr = "0.1.3"

编辑main.rs:

extern crate dbr;

use std::ffi::CStr;
use std::ffi::CString;
use std::os::raw::c_char;
use std::env;

use dbr::reader::*;

extern "C" fn callback(index: i32, barcode_type: *const c_char, barcode_value: *const c_char) {
    unsafe {
        println!(
            "Index {}, {}, {}",
            index,
            CStr::from_ptr(barcode_type).to_str().unwrap(),
            CStr::from_ptr(barcode_value).to_str().unwrap()
        );
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() == 1 {
        println!("Please input an image file.");
        return
    }

    println!("Hello Dynamsoft Barcode Reader!");
    unsafe {
        register_callback(Some(callback));
        let image_file = CString::new(env::args().nth(1).expect("Missing argument")).unwrap();
        let license = CString::new("t0068NQAAAFKYHV9xSZDEThUtClXNzxXH9TLSj/vYcY8mSKa0RxaGw3qNynyAMJ9Ib8UPxzFsbAMIugqPO313BvfiOdmZFTY=").unwrap();
        c_decodeFile(image_file.as_ptr(), license.as_ptr());
    }

    println!("Bye!");
}

运行程序:

cargo run <image file>

源码

https://github.com/dynamsoft-dbr/rust


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
灰度变换_MATLAB发布时间:2022-07-18
下一篇:
AWS 赞助 Rust 中文社区创业者发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap