Building a wrapper for a C library: recommendations

I'm writing an optimization application, where I need to interface with a C++ library for the mathematical optimisation routines. The library exposes a C interface which I plan to use through a wrapper. I've generated bindings with bindgen and am able to compile and run basic stuff.

Looking around, I've found a lot of warnings/caveats around using unsafe code, hence I'd like your views on my approach.

Here is a typical function that I have to use - this returns a sequence of solution values

extern "C" {
    pub fn Cbc_getColSolution(model: *mut Cbc_Model) -> *const f64;
}

Here is what I've wrapped it around:

...
        let mut soln_vec: Vec<f64> = Vec::new();
        unsafe {
            let soln = cbc::Cbc_getColSolution(self.model);
            let ncols = //get the number of elements;
            for i in 0..ncols {
                soln_vec.push(*soln.offset(i as isize));
            }
        }
... 
//return the soln_vec

Any suggestions on how to do this safer and/or faster?

Secondly, I need to also wrap "set*" methods, where I'll have to convert a Vec to a *const f64. What is the recommended approach?

This looks opposite to "for the mathematical optimisation routines".
You can use from_raw_parts in std::slice - Rust to not allocate/copy data.

To be pedantic the std::slice::from_raw_parts neither allocate nor copy data. It just transmute the ptr and the len into the &[T] type, assuming given memory location is valid and well aligned and filled with initialized and valid and alive values.

Yeah, I missed not.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.