|
2 | 2 | // Copyright 2019 The EVMC Authors. |
3 | 3 | // Licensed under the Apache License, Version 2.0. |
4 | 4 |
|
| 5 | +use std::ffi::{CStr, CString}; |
| 6 | + |
5 | 7 | mod sys; |
6 | 8 |
|
| 9 | +pub fn load_and_configure( |
| 10 | + config: &str, |
| 11 | +) -> Result<*mut sys::evmc_vm, (sys::evmc_loader_error_code, String)> { |
| 12 | + let config_cstr = CString::new(config).unwrap(); |
| 13 | + let mut error_code = sys::evmc_loader_error_code::EVMC_LOADER_UNSPECIFIED_ERROR; |
| 14 | + let instance = unsafe { sys::evmc_load_and_configure(config_cstr.as_ptr(), &mut error_code) }; |
| 15 | + |
| 16 | + if error_code == sys::evmc_loader_error_code::EVMC_LOADER_SUCCESS { |
| 17 | + assert!(!instance.is_null()); |
| 18 | + Ok(instance) |
| 19 | + } else { |
| 20 | + assert!(instance.is_null()); |
| 21 | + let error_msg = unsafe { CStr::from_ptr(sys::evmc_last_error_msg()) } |
| 22 | + .to_str() |
| 23 | + .expect("well formed error message") // TODO free the vm |
| 24 | + .to_string(); |
| 25 | + Err((error_code, error_msg)) |
| 26 | + } |
| 27 | +} |
| 28 | + |
7 | 29 | #[cfg(test)] |
8 | 30 | mod tests { |
9 | | -use std::ffi::CString; |
10 | | -use std::os::raw::c_char; |
| 31 | + use std::ffi::CString; |
| 32 | + use std::os::raw::c_char; |
11 | 33 |
|
12 | 34 | use super::*; |
13 | 35 |
|
14 | 36 | #[test] |
15 | 37 | fn load_fail() { |
16 | | - let c_str = CString::new("test.so").unwrap(); |
17 | | - unsafe { |
18 | | - let mut error_code = sys::evmc_loader_error_code::EVMC_LOADER_UNSPECIFIED_ERROR; |
19 | | - let instance = sys::evmc_load_and_create(c_str.as_ptr() as *const c_char, &mut error_code); |
20 | | - println!("{:?}", error_code); |
21 | | - } |
| 38 | + println!("{:?}", load_and_configure("test.so")); |
22 | 39 | } |
23 | 40 | } |
0 commit comments