Skip to content

Instantly share code, notes, and snippets.

@anowell
Created July 21, 2016 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anowell/21fa62f28854c3ee8ef896d6bea97cfa to your computer and use it in GitHub Desktop.
Save anowell/21fa62f28854c3ee8ef896d6bea97cfa to your computer and use it in GitHub Desktop.
Minimal wkhtmltopdf snippet that works in debug but segfaults in --release
extern crate libwkhtmltox_sys as libwkhtmltox; // https://github.com/anowell/libwkhtmltox-sys
use libwkhtmltox::*;
use std::ffi::{CString, CStr};
use std::os::raw::{c_char, c_int, c_uchar};
unsafe extern fn finished_callback(converter: *mut wkhtmltopdf_converter, val: c_int) {
println!("finished_callback: {}", val);
// Read the PDF output
let buf_ptr: *mut *const c_uchar = std::mem::uninitialized();
println!("calling wkhtmltopdf_get_output");
let bytes = wkhtmltopdf_get_output(converter, buf_ptr) as usize;
println!("output received");
let buf_slice = std::slice::from_raw_parts(*buf_ptr as *const c_uchar, bytes);
println!("buf_slice.len={}", buf_slice.len());
}
unsafe extern fn error_callback(_converter: *mut wkhtmltopdf_converter, ptr: *const c_char) {
let cstr = CStr::from_ptr(ptr);
let msg = cstr.to_string_lossy().into_owned();
println!("error_callback: {}", msg);
}
fn main() {
unsafe {
if wkhtmltopdf_init(0) != 1 {
panic!("init failed");
}
let global_settings = wkhtmltopdf_create_global_settings();
let object_settings = wkhtmltopdf_create_object_settings();
let converter = wkhtmltopdf_create_converter(global_settings);
// Setup callbacks
wkhtmltopdf_set_finished_callback(converter, Some(finished_callback));
wkhtmltopdf_set_error_callback(converter, Some(error_callback));
// Perform the conversion
let c_html = CString::new(r##"<b>foo</b>bar"##).expect("null byte found");
wkhtmltopdf_add_object(converter, object_settings, c_html.as_ptr());
if wkhtmltopdf_convert(converter) != 1 {
panic!("wktmltopdf_convert failed");
}
// Wait a bitfor the callbacks a chance to run
std::thread::sleep(std::time::Duration::from_secs(4));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment