Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mat should have non-owning counterpart #110

Open
vadixidav opened this issue Mar 5, 2019 · 3 comments
Open

Mat should have non-owning counterpart #110

vadixidav opened this issue Mar 5, 2019 · 3 comments

Comments

@vadixidav
Copy link

In the documentation I found from_buffer. This method indicates that it is possible to actually invoke a double-free without doing anything. Additionally, the source of from_buffer doesn't check to see if the slice is big enough! This means that undefined behavior and segfaults could happen.

To fix this, we should create a SliceMat. This would be a cv::Mat that does not own its data. It would be templated with a lifetime param <'a> so that when it is created from a slice it wont be allowed to outlive the slice due to the Rust borrow checker. We then also need to make a newtype wrapper around just the cv::Mat pointer that opencv has and move all the shared functionality we have into there. We can call this wrapper MatRef. We then impl Deref<MatRef> for Mat and impl Deref<MatRef> for SliceMat.

@Pzixel
Copy link
Collaborator

Pzixel commented Mar 6, 2019

IIRC from_buffer copies its data but I may be wrong here.

Checking array length cannot be done before Mat is constructed because different CvType require different buffer size. Only opencv itself could tell us if buffer if big enough so I think it's better to just handle OutOfBoundException in C++ or something, and return Result istead of mat.

@vadixidav
Copy link
Author

Oh, I see, so right now it is just undefined behavior if your buffer is the wrong size. I will create the appropriate unit tests then and change this to get back a Result.

@Pzixel
Copy link
Collaborator

Pzixel commented Mar 6, 2019

There are some hepers class (CResult, in instance) that helps you to convert C++ Exception into rust Result. See

cv-rs/native/common.h

Lines 68 to 87 in b602103

// Caller is responsible for disposing `error` field
template <typename T>
struct Result {
T value;
CDisposableString error;
static Result<T> FromFunction(std::function<T()> function) {
T value;
char* error = nullptr;
try {
value = function();
} catch (cv::Exception& e) {
const char* err_msg = e.what();
auto len = std::strlen(err_msg);
error = new char[len + 1];
std::strcpy(error, err_msg);
}
return Result<T>{value, CDisposableString{error}};
}
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants