Reputation: 994
The following code is in Rust:
#[no_mangle]
#[cfg(not(target_arch = "wasm32"))]
pub extern fn generate_work(input_hash: &str, max_iters: Option<u64>) -> Option<String> {
let bytes = Vec::from_hex(input_hash).unwrap();
generate_work_internal(&bytes[..], max_iters)
}
I have the following code in C#:
[DllImport("mydll.dll")]
private static extern string generate_work(string input_hash, ulong[] max_iters);
I'm getting the error:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
I have tried other signatures, but none has worked.
Upvotes: 3
Views: 1139
Reputation: 430645
As described in my FFI Omnibus, you cannot pass complicated Rust-specific types via FFI functions. You must use only types that are known to the C ABI. In your example, these types are not known:
&str
Option
String
Instead, you will be required to only use basic C pointers. A NULL pointer can represent None
for a string, but for an Option<u64>
, you will need to break it up into two values, a boolean and the real value. Your FFI function will look something like:
extern crate libc;
use std::ffi::{CStr, CString};
use std::ptr;
#[no_mangle]
#[cfg(not(target_arch = "wasm32"))]
pub extern "C" fn generate_work(
input_hash: *const libc::c_char,
max_iters_present: bool,
max_iters: u64,
) -> *const libc::c_char {
let input_hash = if input_hash.is_null() {
return ptr::null();
} else {
unsafe { CStr::from_ptr(input_hash) }
};
let input_hash = match input_hash.to_str() {
Ok(s) => s,
Err(_) => return ptr::null(),
};
let max_iters = if max_iters_present {
Some(max_iters)
} else {
None
};
let result = inner_code(input_hash, max_iters);
match result {
Some(s) => {
match CString::new(s) {
Ok(s) => s.into_raw(),
Err(_) => ptr::null(),
}
},
None => ptr::null(),
}
}
Note that this returns an allocated string that you need to pass back to Rust to deallocate. Again, as described in the FFI Omnibus, you'll need something like
#[no_mangle]
pub extern fn free_a_string(s: *mut c_char) {
unsafe {
if s.is_null() { return }
CString::from_raw(s)
};
}
Converting a string to Rust is easy:
[DllImport("string_arguments", EntryPoint="how_many_characters")]
public static extern uint HowManyCharacters(string s);
Returning a string requires a lot more trickery, sadly:
internal class Native
{
[DllImport("string_return")]
internal static extern ThemeSongHandle theme_song_generate(byte length);
[DllImport("string_return")]
internal static extern void theme_song_free(IntPtr song);
}
internal class ThemeSongHandle : SafeHandle
{
public ThemeSongHandle() : base(IntPtr.Zero, true) {}
public override bool IsInvalid
{
get { return false; }
}
public string AsString()
{
int len = 0;
while (Marshal.ReadByte(handle, len) != 0) { ++len; }
byte[] buffer = new byte[len];
Marshal.Copy(handle, buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer);
}
protected override bool ReleaseHandle()
{
Native.theme_song_free(handle);
return true;
}
}
See also:
CStr
CString
Upvotes: 4