title: How to wrap a call to a FFI function that uses VarArgs in Rust?
body: <p><code>mexPrintf</code>, just like <code>printf</code>, accepts a varargs list of arguments, but I don't know what the best way to wrap this is in Rust. There is a <a href="https://github.com/rust-lang/rfcs/issues/376" rel="nofollow noreferrer">RFC for variadic generics</a>, but what can we do today?</p>
  
  <p>In this example, I want to print of the number of inputs and outputs, but the wrapped function just prints garbage. Any idea how to fix this?</p>
  
  <p><a href="https://i.stack.imgur.com/5SRYq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5SRYq.png" alt="enter image description here"></a></p>
  
  <pre><code>#![allow(non_snake_case)]
  #![allow(unused_variables)]
  
  extern crate mex_sys;
  
  use mex_sys::mxArray;
  use std::ffi::CString;
  use std::os::raw::c_int;
  use std::os::raw::c_void;
  
  type VarArgs = *mut c_void;
  
  // attempt to wrap mex_sys::mexPrintf
  fn mexPrintf(fmt: &amp;str, args: VarArgs) {
      let cs = CString::new(fmt).unwrap();
      unsafe {
          mex_sys::mexPrintf(cs.as_ptr(), args);
      }
  }
  
  #[no_mangle]
  pub extern "system" fn mexFunction(
      nlhs: c_int,
      plhs: *mut *mut mxArray,
      nrhs: c_int,
      prhs: *mut *mut mxArray,
  ) {
      let hw = CString::new("hello world\n").unwrap();
      unsafe {
          mex_sys::mexPrintf(hw.as_ptr());
      }
  
      let inout = CString::new("%d inputs and %d outputs\n").unwrap();
      unsafe {
          mex_sys::mexPrintf(inout.as_ptr(), nrhs, nlhs);
      }
  
      mexPrintf("hello world wrapped\n", std::ptr::null_mut());
  
      let n = Box::new(nrhs);
      let p = Box::into_raw(n);
      mexPrintf("inputs %d\n", p as VarArgs);
  
      let mut v = vec![3];
      mexPrintf("vec %d\n", v.as_mut_ptr() as VarArgs);
  }
  </code></pre>