reorganize modules for better IDE discoverability, switch to edition 2018
MODIFY
Cargo.toml
Cargo.toml
@@ -7,6 +7,7 @@ readme = "README.md"
keywords = [ "opencv", "vision" ]
license = "WTFPL"
version = "0.2.5-alpha.0"
+edition = "2018"
authors = ["Mathieu Poumeyrol <kali@zoy.org>"]
build = "build.rs"

MODIFY
build.rs
build.rs
-extern crate cc;
-extern crate glob;
-extern crate pkg_config;
-
-use glob::glob;
use std::ffi::OsString;
-use std::fs;
-use std::fs::{read_dir, File};
+use std::{fs, io};
+use std::fs::{File, read_dir};
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
+use glob::glob;
+
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=gen_rust.py");
- let out_dir = std::env::var("OUT_DIR").unwrap();
+ let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
+ let out_dir_as_str = out_dir.to_str().unwrap();
+ let hub_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src");
+ let module_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/hub");
let opencv = pkg_config::Config::new().cargo_metadata(false).probe("opencv").unwrap();
let mut search_paths = opencv.include_paths.clone();
@@ -32,8 +32,8 @@ fn main() {
let third_party_dir = format!("{}/share/OpenCV/3rdparty/lib", pkg_config::Config::get_variable("opencv", "prefix").unwrap());
println!("cargo:rustc-link-search=native={}", third_party_dir);
- println!("OpenCV lives in {:?}", actual_opencv);
- println!("Generating code in {:?}", out_dir);
+ println!("OpenCV lives in {}", opencv_dir.display());
+ println!("Generating code in {}", out_dir_as_str);
println!("cargo:rerun-if-changed=gen_rust.py");
println!("cargo:rerun-if-changed=hdr_parser.py");
@@ -54,7 +54,7 @@ fn main() {
gcc.include(path);
}
- for entry in glob(&(out_dir.clone() + "/*")).unwrap() {
+ for entry in glob(&format!("{}/*", out_dir_as_str)).unwrap() {
fs::remove_file(entry.unwrap()).unwrap()
}
@@ -132,29 +132,29 @@ fn main() {
)
.collect::<Vec<(String,Vec<String>)>>();
- let mut types = PathBuf::from(&out_dir);
- types.push("common_opencv.h");
{
- let mut types = File::create(types).unwrap();
- for ref m in modules.iter() {
- write!(&mut types, "#include <opencv2/{}.hpp>\n", &*m.0).unwrap();
+ let mut types = File::create(out_dir.join("common_opencv.h")).unwrap();
+ for m in &modules {
+ write!(&mut types, "#include <opencv2/{}.hpp>\n", m.0).unwrap();
+ if m.0 == "dnn" {
+ // include it manually, otherwise it's not included
+ write!(&mut types, "#include <opencv2/{}/all_layers.hpp>\n", m.0).unwrap();
+ }
}
}
- let mut types = PathBuf::from(&out_dir);
- types.push("types.h");
{
- let mut types = File::create(types).unwrap();
+ let mut types = File::create(out_dir.join("types.h")).unwrap();
write!(&mut types, "#include <cstddef>\n").unwrap();
}
- for ref module in modules.iter() {
- let mut cpp = PathBuf::from(&out_dir);
+ for module in &modules {
+ let mut cpp = out_dir.clone();
cpp.push(&*module.0);
cpp.set_extension("cpp");
if !Command::new("python2.7")
- .args(&["gen_rust.py", "hdr_parser.py", &*out_dir, &*module.0])
+ .args(&["gen_rust.py", "hdr_parser.py", out_dir_as_str, out_dir_as_str, &module.0])
.args(
&(module
.1
@@ -172,16 +172,34 @@ fn main() {
{
panic!();
}
- let _ = fs::remove_file("gen_rust.pyc");
- let _ = fs::remove_file("hdr_parser.pyc");
gcc.file(cpp);
+ let e = Command::new("sh")
+ .current_dir(&out_dir)
+ .arg("-c")
+ .arg(format!(
+ "g++ {}.consts.cpp -o {}.consts `pkg-config --cflags --libs opencv` -L`pkg-config --variable=prefix opencv`/share/OpenCV/3rdparty/lib",
+ module.0, module.0
+ ))
+ .status()
+ .unwrap();
+ assert!(e.success());
+ let e = Command::new("sh")
+ .current_dir(&out_dir)
+ .arg("-c")
+ .arg(format!("./{}.consts >> {}.rs", module.0, module.0))
+ .status()
+ .unwrap();
+ assert!(e.success());
+ let _ = fs::remove_file(out_dir.join(format!("{}.consts", module.0)));
+ let _ = fs::remove_file(out_dir.join(format!("{}.consts.cpp", module.0)));
}
+ let _ = fs::remove_file("gen_rust.pyc");
+ let _ = fs::remove_file("hdr_parser.pyc");
- let mut return_types = PathBuf::from(&out_dir);
- return_types.push("return_types.h");
- let mut hub_return_types = File::create(return_types).unwrap();
- for entry in glob(&(out_dir.clone() + "/cv_return_value_*.type.h")).unwrap() {
+ {
+ let mut hub_return_types = File::create(out_dir.join("return_types.h")).unwrap();
+ for entry in glob(&format!("{}/cv_return_value_*.type.h", out_dir_as_str)).unwrap() {
writeln!(
&mut hub_return_types,
r#"#include "{}""#,
@@ -189,79 +207,64 @@ fn main() {
)
.unwrap();
}
+ }
for entry in glob("native/*.cpp").unwrap() {
gcc.file(entry.unwrap());
}
- for entry in glob(&(out_dir.clone() + "/*.type.cpp")).unwrap() {
+ for entry in glob(&format!("{}/*.type.cpp", out_dir_as_str)).unwrap() {
gcc.file(entry.unwrap());
}
gcc.include(".")
- .include(&out_dir)
- .flag("-Wno-c++11-extensions");
+ .include(&out_dir);
- for ref module in &modules {
- let e = Command::new("sh")
- .current_dir(&out_dir)
- .arg("-c")
- .arg(format!(
- "g++ {}.consts.cpp -o {}.consts `pkg-config --cflags --libs opencv` -L`pkg-config --variable=prefix opencv`/share/OpenCV/3rdparty/lib",
- module.0, module.0
- ))
- .status()
- .unwrap();
- assert!(e.success());
- let e = Command::new("sh")
- .current_dir(&out_dir)
- .arg("-c")
- .arg(format!("./{}.consts > {}.consts.rs", module.0, module.0))
- .status()
- .unwrap();
- assert!(e.success());
+ gcc.compile("ocvrs");
+
+ if !module_dir.exists() {
+ fs::create_dir(&module_dir).unwrap();
}
- gcc.compile("ocvrs");
+ for entry in glob(&format!("{}/*", module_dir.to_str().unwrap())).unwrap() {
+ let _ = fs::remove_file(entry.unwrap());
+ }
- let mut hub_filename = PathBuf::from(&out_dir);
- hub_filename.push("hub.rs");
{
- let mut hub = File::create(hub_filename).unwrap();
+ let mut hub = File::create(hub_dir.join("hub.rs")).unwrap();
for ref module in &modules {
writeln!(&mut hub, r#"pub mod {};"#, module.0).unwrap();
+ fs::rename(out_dir.join(format!("{}.rs", module.0)), module_dir.join(format!("{}.rs", module.0))).unwrap();
}
- writeln!(&mut hub, r#"pub mod types {{"#).unwrap();
- writeln!(&mut hub, " use libc::{{ c_void, c_char, size_t }};").unwrap();
- for entry in glob(&(out_dir.clone() + "/*.type.rs")).unwrap() {
- writeln!(
- &mut hub,
- r#" include!(concat!(env!("OUT_DIR"), "/{}"));"#,
- entry.unwrap().file_name().unwrap().to_str().unwrap()
- )
- .unwrap();
+ writeln!(&mut hub, "pub mod types;").unwrap();
+ writeln!(&mut hub, "#[doc(hidden)] pub mod sys;").unwrap();
}
- writeln!(&mut hub, r#"}}"#).unwrap();
- writeln!(&mut hub, "#[doc(hidden)] pub mod sys {{").unwrap();
- writeln!(&mut hub, " use libc::{{ c_void, c_char, size_t }};").unwrap();
- for entry in glob(&(out_dir.clone() + "/*.rv.rs")).unwrap() {
- writeln!(
- &mut hub,
- r#" include!(concat!(env!("OUT_DIR"), "/{}"));"#,
- entry.unwrap().file_name().unwrap().to_str().unwrap()
- )
- .unwrap();
+
+ {
+ let mut types = File::create(module_dir.join("types.rs")).unwrap();
+ writeln!(&mut types, "use libc::{{c_void, c_char, size_t}};").unwrap();
+ writeln!(&mut types, "use crate::{{core, types}};").unwrap();
+ for entry in glob(&format!("{}/*.type.rs", out_dir_as_str)).unwrap() {
+ let entry = entry.unwrap();
+ io::copy(&mut File::open(&entry).unwrap(), &mut types).unwrap();
+ let _ = fs::remove_file(entry);
}
- for ref module in &modules {
- writeln!(
- &mut hub,
- r#" include!(concat!(env!("OUT_DIR"), "/{}.externs.rs"));"#,
- module.0
- )
- .unwrap();
}
- writeln!(&mut hub, "}}\n").unwrap();
+
+ {
+ let mut sys = File::create(module_dir.join("sys.rs")).unwrap();
+ writeln!(&mut sys, "use libc::{{c_void, c_char, size_t}};").unwrap();
+ writeln!(&mut sys, "use crate::{{core}};").unwrap();
+ for entry in glob(&format!("{}/*.rv.rs", out_dir_as_str)).unwrap() {
+ let entry = entry.unwrap();
+ io::copy(&mut File::open(&entry).unwrap(), &mut sys).unwrap();
+ let _ = fs::remove_file(entry);
+ }
+ for module in &modules {
+ let path = out_dir.join(format!("{}.externs.rs", module.0));
+ io::copy(&mut File::open(&path).unwrap(), &mut sys).unwrap();
+ let _ = fs::remove_file(path);
+ }
}
- println!("cargo:rustc-link-lib=ocvrs");
// now, this is a nightmare.
// opencv will embark these as .a when they are not available, or

MODIFY
examples/video_capture.rs
examples/video_capture.rs
@@ -6,20 +6,20 @@ use opencv::videoio;
fn run() -> Result<(), String> {
let window = "video capture";
- try!(highgui::named_window(window, 1));
- let mut cam = try!(videoio::VideoCapture::index(1));
- let opened = try!(videoio::VideoCapture::is_opened(&cam));
+ highgui::named_window(window, 1)?;
+ let mut cam = videoio::VideoCapture::index(1)?;
+ let opened = videoio::VideoCapture::is_opened(&cam)?;
if !opened {
println!("Using different camera");
- cam = try!(videoio::VideoCapture::index(0));
+ cam = videoio::VideoCapture::index(0)?;
}
loop {
- let mut frame = try!(core::Mat::new());
- try!(cam.read(&mut frame));
- if try!(frame.size()).width > 0 {
- try!(highgui::imshow(window, &mut frame));
+ let mut frame = core::Mat::new()?;
+ cam.read(&mut frame)?;
+ if frame.size()?.width > 0 {
+ highgui::imshow(window, &mut frame)?;
}
- if try!(highgui::wait_key(10)) > 0 {
+ if highgui::wait_key(10)? > 0 {
break;
}
}

MODIFY
examples/video_facedetect.rs
examples/video_facedetect.rs
@@ -8,30 +8,30 @@ use opencv::videoio;
fn run() -> Result<(), String> {
let window = "video capture";
let xml = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml";
- try!(highgui::named_window(window, 1));
- let mut cam = try!(videoio::VideoCapture::index(1));
- let opened = try!(videoio::VideoCapture::is_opened(&cam));
+ highgui::named_window(window, 1)?;
+ let mut cam = videoio::VideoCapture::index(1)?;
+ let opened = videoio::VideoCapture::is_opened(&cam)?;
if !opened {
println!("Using different camera");
- cam = try!(videoio::VideoCapture::index(0));
+ cam = videoio::VideoCapture::index(0)?;
}
- let mut face = try!(objdetect::CascadeClassifier::new(xml));
+ let mut face = objdetect::CascadeClassifier::new(xml)?;
loop {
- let mut frame = try!(core::Mat::new());
- try!(cam.read(&mut frame));
- if try!(frame.size()).width == 0 {
+ let mut frame = core::Mat::new()?;
+ cam.read(&mut frame)?;
+ if frame.size()?.width == 0 {
::std::thread::sleep(::std::time::Duration::from_secs(50));
continue;
}
- let mut gray = try!(core::Mat::new());
- try!(imgproc::cvt_color(
+ let mut gray = core::Mat::new()?;
+ imgproc::cvt_color(
&frame,
&mut gray,
imgproc::COLOR_BGR2GRAY,
0
- ));
- let mut reduced = try!(core::Mat::new());
- try!(imgproc::resize(
+ )?;
+ let mut reduced = core::Mat::new()?;
+ imgproc::resize(
&gray,
&mut reduced,
core::Size {
@@ -41,9 +41,9 @@ fn run() -> Result<(), String> {
0.25f64,
0.25f64,
imgproc::INTER_LINEAR
- ));
+ )?;
let mut faces = ::opencv::types::VectorOfRect::new();
- try!(face.detect_multi_scale(
+ face.detect_multi_scale(
&reduced,
&mut faces,
1.1,
@@ -57,7 +57,7 @@ fn run() -> Result<(), String> {
width: 0,
height: 0
}
- ));
+ )?;
println!("faces: {}", faces.len());
for face in faces.iter() {
println!("face {:?}", face);
@@ -67,7 +67,7 @@ fn run() -> Result<(), String> {
width: face.width * 4,
height: face.height * 4,
};
- try!(imgproc::rectangle(
+ imgproc::rectangle(
&frame,
scaled_face,
core::Scalar {
@@ -76,10 +76,10 @@ fn run() -> Result<(), String> {
1,
8,
0
- ));
+ )?;
}
- try!(highgui::imshow(window, &frame));
- if try!(highgui::wait_key(10)) > 0 {
+ highgui::imshow(window, &frame)?;
+ if highgui::wait_key(10)? > 0 {
break;
}
}

MODIFY
examples/video_features.rs
examples/video_features.rs
@@ -9,14 +9,14 @@ use opencv::features2d::Feature2D;
fn run() -> Result<(), String> {
let window = "video capture";
- try!(highgui::named_window(window, 1));
- let mut cam = try!(videoio::VideoCapture::index(1));
- let opened = try!(videoio::VideoCapture::is_opened(&cam));
+ highgui::named_window(window, 1)?;
+ let mut cam = videoio::VideoCapture::index(1)?;
+ let opened = videoio::VideoCapture::is_opened(&cam)?;
if !opened {
println!("Using different camera");
- cam = try!(videoio::VideoCapture::index(0));
+ cam = videoio::VideoCapture::index(0)?;
}
- let mut orb = try!(features2d::ORB::create(
+ let mut orb = features2d::ORB::create(
500,
1.2f32,
8,
@@ -25,33 +25,33 @@ fn run() -> Result<(), String> {
2,
features2d::ORB_HARRIS_SCORE,
31
- ));
+ )?;
loop {
- let mut frame = try!(core::Mat::new());
- try!(cam.read(&mut frame));
- if try!(frame.size()).width > 0 {
- let mut gray = try!(core::Mat::new());
- try!(imgproc::cvt_color(
+ let mut frame = core::Mat::new()?;
+ cam.read(&mut frame)?;
+ if frame.size()?.width > 0 {
+ let mut gray = core::Mat::new()?;
+ imgproc::cvt_color(
&frame,
&mut gray,
imgproc::COLOR_BGR2GRAY,
0
- ));
+ )?;
let mut kps = opencv::types::VectorOfKeyPoint::new();
// let mut desc = try!(core::Mat::new());
- let mask = try!(core::Mat::new());
- try!(orb.detect(&gray, &mut kps, &mask));
- let mut display = try!(core::Mat::new());
- try!(features2d::draw_keypoints(
+ let mask = core::Mat::new()?;
+ orb.detect(&gray, &mut kps, &mask)?;
+ let mut display = core::Mat::new()?;
+ features2d::draw_keypoints(
&gray,
&kps,
&mut display,
core::Scalar { data: [-1f64; 4] },
features2d::DrawMatchesFlags_DEFAULT
- ));
- try!(highgui::imshow(window, &display));
+ )?;
+ highgui::imshow(window, &display)?;
}
- if try!(highgui::wait_key(10)) > 0 {
+ if highgui::wait_key(10)? > 0 {
break;
}
}

MODIFY
examples/video_to_gray.rs
examples/video_to_gray.rs
extern crate opencv;
use opencv::core;
-use opencv::imgproc;
use opencv::highgui;
+use opencv::imgproc;
use opencv::videoio;
fn run() -> Result<(), String> {
let window = "video capture";
- try!(highgui::named_window(window, 1));
- let mut cam = try!(videoio::VideoCapture::index(1));
- let opened = try!(videoio::VideoCapture::is_opened(&cam));
+ highgui::named_window(window, 1)?;
+ let mut cam = videoio::VideoCapture::index(1)?;
+ let opened = videoio::VideoCapture::is_opened(&cam)?;
if !opened {
println!("Using different camera");
- cam = try!(videoio::VideoCapture::index(0));
+ cam = videoio::VideoCapture::index(0)?;
}
loop {
- let mut frame = try!(core::Mat::new());
- try!(cam.read(&mut frame));
- if try!(frame.size()).width > 0 {
- let mut gray = try!(core::Mat::new());
- try!(imgproc::cvt_color(
+ let mut frame = core::Mat::new()?;
+ cam.read(&mut frame)?;
+ if frame.size()?.width > 0 {
+ let mut gray = core::Mat::new()?;
+ imgproc::cvt_color(
&frame,
&mut gray,
imgproc::COLOR_BGR2GRAY,
0
- ));
- try!(highgui::imshow(window, &gray));
+ )?;
+ highgui::imshow(window, &gray)?;
}
- if try!(highgui::wait_key(10)) > 0 {
+ if highgui::wait_key(10)? > 0 {
break;
}
}

MODIFY
gen_rust.py
gen_rust.py
@@ -417,6 +417,8 @@ for s in [2,3,4,6]:
for t in [("uchar","b"),("short","s"),("int","i"),("double","d"),("float","f")]:
value_struct_types["Vec%d%s"%(s,t[1])] = ("data", "%s[%d]"%(t[0],s)),
+static_modules = ("sys", "types", "core")
+
#
# TEMPLATES
#
@@ -779,7 +781,7 @@ class FuncInfo(GeneralInfo):
io.write("%sfn %s(%s) -> Result<%s,String> {\n"%(pub, self.r_name(), ", ".join(args), self.rv_type().rust_full))
io.write("// identifier: %s\n"%(self.identifier))
io.write(" unsafe {\n")
- io.write(" let rv = ::sys::%s(%s);\n"%(self.c_name(), ", ".join(call_args)))
+ io.write(" let rv = sys::%s(%s);\n"%(self.c_name(), ", ".join(call_args)))
io.write(" if rv.error_msg as i32 != 0i32 {\n")
io.write(" let v = CStr::from_ptr(rv.error_msg).to_bytes().to_vec();\n")
io.write(" ::libc::free(rv.error_msg as *mut c_void);\n")
@@ -1053,7 +1055,7 @@ class SimpleClassTypeInfo(TypeInfo):
self.rust_local = typeid.replace("cv::","").replace("::", "_")
self.sane = self.rust_local
if self.ci:
- self.rust_full = "::" + self.ci.module + "::" + self.rust_local
+ self.rust_full = ("super::" if self.ci.module not in static_modules else "") + self.ci.module + "::" + self.rust_local
self.ctype = "c_" + self.rust_local
self.c_sane = self.ctype
self.rust_extern = self.rust_full
@@ -1077,7 +1079,7 @@ class ValueStructTypeInfo(TypeInfo):
self.cpptype = typeid
self.rust_local = typeid.replace("cv::","")
self.sane = self.rust_local
- self.rust_full = "::core::" + self.rust_local
+ self.rust_full = "core::" + self.rust_local
self.ctype = "c_" + self.rust_local
self.c_sane = self.ctype
self.rust_extern = self.rust_full
@@ -1099,7 +1101,7 @@ class BoxedClassTypeInfo(TypeInfo):
self.cpptype = self.ci.nested_cppname
self.rust_extern = "*mut c_void"
self.rust_local = typeid.replace("cv::","").replace("::", "_")
- self.rust_full = "::" + self.ci.module + "::" + self.rust_local
+ self.rust_full = ("super::" if self.ci.module not in static_modules else "") + self.ci.module + "::" + self.rust_local
self.is_by_ptr = True
self.is_trait = typeid in forced_trait_classes or self.ci.is_trait
self.ctype = "void*"
@@ -1126,12 +1128,12 @@ class VectorTypeInfo(TypeInfo):
self.inner_cpptype = inner.cpptype
self.cpptype = "std::vector<%s>" % (inner.cpptype)
self.sane = self.rust_local = "VectorOf"+inner.sane
- self.rust_full = "::types::" + self.rust_local
+ self.rust_full = "types::" + self.rust_local
self.rust_extern = "*mut c_void"
self.inner_rust_full = inner.rust_full
def gen_wrapper(self):
- with open(self.gen.output_path + "/" + self.sane + ".type.rs", "w") as f:
+ with open(self.gen.rust_dir + "/" + self.sane + ".type.rs", "w") as f:
if self.inner.typeid != "bool":
f.write(template("""
extern "C" {
@@ -1169,7 +1171,7 @@ class VectorTypeInfo(TypeInfo):
}
""").substitute(self.__dict__))
if isinstance(self.inner, BoxedClassTypeInfo) or self.inner.is_by_ptr:
- with open(self.gen.output_path + "/" + self.sane + ".type.rs", "a") as f:
+ with open(self.gen.rust_dir + "/" + self.sane + ".type.rs", "a") as f:
f.write(template("""
// BoxedClassTypeInfo
impl $rust_full {
@@ -1194,7 +1196,7 @@ class VectorTypeInfo(TypeInfo):
}
""").substitute(self.__dict__))
else:
- with open(self.gen.output_path+"/"+self.sane+".type.rs", "a") as f:
+ with open(self.gen.rust_dir + "/" + self.sane + ".type.rs", "a") as f:
f.write(template("""
impl $rust_full {
pub fn push(&mut self, val: $inner_rust_full) {
@@ -1220,7 +1222,7 @@ class VectorTypeInfo(TypeInfo):
}
}
""").substitute(self.__dict__))
- with open(self.gen.output_path+"/"+self.sane+".type.cpp", "w") as f:
+ with open(self.gen.cpp_dir + "/" + self.sane + ".type.cpp", "w") as f:
externs = template("""
void* cv_new_$sane() { return new $cpptype(); }
void cv_delete_$sane(void* ptr) { delete (($cpptype*) ptr); }
@@ -1272,12 +1274,12 @@ class SmartPtrTypeInfo(TypeInfo):
self.cpptype = self.inner.cpptype
self.outer_cpptype = "Ptr<"+self.inner.cpptype+">"
self.rust_local = self.sane = "PtrOf" + inner.sane
- self.rust_full = "::types::" + self.rust_local
+ self.rust_full = "types::" + self.rust_local
self.inner_rust_full = inner.rust_full
self.inner_local = inner.rust_local
def gen_wrapper(self):
- with open(self.gen.output_path + "/" + self.rust_local + ".type.rs", "w") as f:
+ with open(self.gen.rust_dir + "/" + self.rust_local + ".type.rs", "w") as f:
f.write(template("""
#[allow(dead_code)]
pub struct $rust_local {
@@ -1309,7 +1311,7 @@ class SmartPtrTypeInfo(TypeInfo):
}
}
""").substitute(rust_name=self.rust_local, base_local=cibase.rust_local, base_full=cibase.rust_full, sane=self.sane))
- with open(self.gen.output_path+"/"+self.sane+".type.cpp", "w") as f:
+ with open(self.gen.cpp_dir + "/" + self.sane + ".type.cpp", "w") as f:
code = template("""
void* cv_${sane}_get(void* ptr) {
return (($outer_cpptype*)ptr)->get();
@@ -1495,13 +1497,21 @@ class RustWrapperGenerator(object):
def register_function(self, f):
self.functions.append(f)
- def gen(self, srcfiles, module, output_path):
- parser = hdr_parser.CppHeaderParser()
- self.output_path = output_path
+ def gen(self, srcfiles, module, cpp_dir, rust_dir):
+ """
+ :param srcfiles:
+ :type module: str
+ :type cpp_dir: str
+ :type rust_dir: str
+ :return:
+ """
+ self.cpp_dir = cpp_dir
+ self.rust_dir = rust_dir
self.module = module
includes = []
- self.namespaces = parser.namespaces
+ parser = hdr_parser.CppHeaderParser()
+ self.namespaces = set(x for x in parser.namespaces)
self.namespaces.add("cv")
for m in cross_modules_deps:
@@ -1541,6 +1551,7 @@ class RustWrapperGenerator(object):
self.moduleSafeRust.write(template("""
use libc::{c_void, c_char, size_t};
use std::ffi::{CStr, CString};
+ use crate::{core, sys, types};
""").substitute())
for co in sorted(self.consts, key=lambda c: c.rustname):
rust = co.gen_rust()
@@ -1551,11 +1562,6 @@ class RustWrapperGenerator(object):
self.moduleSafeRust.write("\n")
- if self.moduleCppConsts.getvalue != "":
- self.moduleSafeRust.write(
- """include!(concat!(env!("OUT_DIR"), "/%s.consts.rs"));\n\n"""%(self.module)
- )
-
for ci in sorted(self.classes.values(), key=lambda ci: ci.fullname):
if ci.classpath:
self.gen_nested_class_decl(ci)
@@ -1584,10 +1590,10 @@ class RustWrapperGenerator(object):
if not ci.is_ignored and not ci.is_ghost:
self.gen_class(ci)
- with open(output_path + "/types.h", "a") as f:
+ with open(cpp_dir + "/types.h", "a") as f:
f.write(self.moduleCppTypes.getvalue())
- with open(output_path + "/" + self.module + ".consts.cpp", "w") as f:
+ with open(cpp_dir + "/" + self.module + ".consts.cpp", "w") as f:
f.write("""#include <cstdio>\n""")
f.write("""#include "opencv2/opencv_modules.hpp"\n""")
f.write("""#include "opencv2/%s.hpp"\n"""%(module))
@@ -1602,18 +1608,18 @@ class RustWrapperGenerator(object):
for namespace in self.namespaces:
if namespace != "":
namespaces += "using namespace %s;\n"%(namespace.replace(".", "::"))
- with open(output_path + "/" + module + ".cpp", "w") as f:
+ with open(cpp_dir + "/" + module + ".cpp", "w") as f:
f.write(template(T_CPP_MODULE).substitute(m = module, M = module.upper(), code = self.moduleCppCode.getvalue(), includes = "\n".join(includes), namespaces=namespaces))
- with open(output_path + "/%s.externs.rs" % (module), "w") as f:
+ with open(rust_dir + "/%s.externs.rs" % (module), "w") as f:
f.write("extern \"C\" {\n")
f.write(self.moduleRustExterns.getvalue())
f.write("}\n")
- with open(output_path + "/" + module + ".rs", "w") as f:
+ with open(rust_dir + "/" + module + ".rs", "w") as f:
f.write(self.moduleSafeRust.getvalue())
- with open(output_path + "/" + module + ".txt", "w") as f:
+ with open(cpp_dir + "/" + module + ".txt", "w") as f:
f.write(self.makeReport())
def makeReport(self):
@@ -1864,7 +1870,7 @@ class RustWrapperGenerator(object):
self.moduleCppTypes.write("} %s;\n\n" % (ci.type_info().c_sane))
def gen_c_return_value_type(self, typ):
- with open(self.output_path + "/cv_return_value_" + typ.c_sane + ".type.h", "w") as f:
+ with open(self.cpp_dir + "/cv_return_value_" + typ.c_sane + ".type.h", "w") as f:
if typ.ctype == "void":
f.write(template("""
// $typeid
@@ -1880,7 +1886,7 @@ class RustWrapperGenerator(object):
$ctype result;
};
""").substitute(typ.__dict__))
- with open(self.output_path + "/cv_return_value_" + typ.c_sane + ".rv.rs", "w") as f:
+ with open(self.rust_dir + "/cv_return_value_" + typ.c_sane + ".rv.rs", "w") as f:
if typ.ctype == "void":
f.write(template("""
// $typeid
@@ -1925,7 +1931,7 @@ class RustWrapperGenerator(object):
}
impl Drop for $rust_full {
fn drop(&mut self) {
- unsafe { ::sys::cv_delete_$sane(self.ptr) };
+ unsafe { sys::cv_delete_$sane(self.ptr) };
}
}
impl $rust_full {
@@ -2014,22 +2020,24 @@ class RustWrapperGenerator(object):
def main():
- dstdir = sys.argv[2]
- module = sys.argv[3]
- srcfiles = sys.argv[4:]
- logging.basicConfig(filename='%s/%s.log' % (dstdir, module), format=None, filemode='w', level=logging.INFO)
+ cpp_dir = sys.argv[2]
+ rust_dir = sys.argv[3]
+ module = sys.argv[4]
+ srcfiles = sys.argv[5:]
+ logging.basicConfig(filename='%s/%s.log' % (cpp_dir, module), format=None, filemode='w', level=logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.WARNING)
logging.getLogger().addHandler(handler)
print("Generating module '" + module + "' from headers:\n\t" + "\n\t".join(srcfiles))
generator = RustWrapperGenerator()
- generator.gen(srcfiles, module, dstdir)
+ generator.gen(srcfiles, module, cpp_dir, rust_dir)
+
if __name__ == "__main__":
- if len(sys.argv) < 4:
+ if len(sys.argv) < 5:
print("Usage:\n", \
os.path.basename(sys.argv[0]), \
- "<full path to hdr_parser.py> <out_dir> <module name> <C++ header> [<C++ header>...]")
+ "<full path to hdr_parser.py> <cpp_out_dir> <rust_out_dir> <module name> <C++ header> [<C++ header>...]")
print("Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv]))
exit(0)

MODIFY
src/lib.rs
src/lib.rs
-#![allow(unused_imports, non_snake_case, dead_code)]
-#![allow(non_upper_case_globals, overflowing_literals)]
-#![allow(non_camel_case_types)]
-extern crate libc;
+pub use self::hub::*;
-use libc::{c_char, c_void, size_t};
-use std::ffi::{CStr, CString};
+#[allow(unused_imports, non_snake_case, dead_code)]
+#[allow(non_upper_case_globals, overflowing_literals)]
+#[allow(non_camel_case_types)]
+mod hub;
-include!(concat!(env!("OUT_DIR"), "/hub.rs"));
-
-pub fn mat() -> ::core::Mat {
- ::core::Mat::new().unwrap()
+pub fn mat() -> core::Mat {
+ core::Mat::new().unwrap()
}

reorganize modules for better IDE discoverability, switch to edition 2018