Usage of unsafe attribute
⚓ Rust 📅 2026-01-11 👤 surdeus 👁️ 1I am trying to compile my rust code into staticlib and I try to write function for use in C# programming langue. This is first time I try it.
I think I only need to export one function for C# code to use my lib, so I wrote this funtion
type Callback = extern "C" fn(u64);
#[no_mangle]
pub extern "C" fn laz2xyz(config_name: *const u8, length: usize, callback: Callback) {
let config_name = unsafe { std::slice::from_raw_parts(config_name, length) };
let config_name = String::from_utf8_lossy(config_name).to_string();
let config_name = std::path::PathBuf::from(config_name);
let xyz = ToXYZ::build(config_name).expect("Failed to initialize ToXYZ");
xyz.run(move |progress| {
callback(progress);
})
.expect("Failed to process files");
}
This function needs to get path to file and callback function. Callback function will report progress of execution to caller.
But I get this error
|
5 | #[no_mangle]
| ^^^^^^^^^ usage of unsafe attribute
|
help: wrap the attribute inunsafe(...)
|
5 | #[unsafe(no_mangle)]
| +++++++ +
But I don't understand why. I never seen #[unsafe(no_mangle)]. All code on internet I seen was using #[no_mangle]
If I change as sugested I get diffirent error
error: this public function might dereference a raw pointer but is not marked
unsafe
--> src\exports\laz2xyz.rs:7:59
|
7 | let config_name = unsafe { std::slice::from_raw_parts(config_name, length) };
|
But this function is inside unsafe block? config_name is marked as problem
![]()
But code does compile. I am using Visual Studio Code
Can this error be false positive?
5 posts - 3 participants
🏷️ Rust_feed