Skip to content

error: extern blocks must be unsafe #4510

Open
@paulclem1

Description

@paulclem1

Describe the Bug

compiler reports "error: extern blocks must be unsafe" on compiling the following
extern "C" {

     fn c_function_name(x: i32) -> i32; 
     //fn c_function_name();
 } 

Even when wrapped in an unsafe loop, the code won't compile. The compiler responds with "error: expected item, found keyword unsafe"
if I wrap the extern C with "unsafe" as directed by the compiler

A clear and concise description of what you expected to happen:

Code should compile with no unsafe wrapping, and, as Ive stated above, compiler responds with a contradictory error if i do exactly what it asks.

I need to implement the extern C to overcome a cc error reported by the compiler. I'm in the process of writing code using the egui_macroquad crate to generate an oscilloscope trace. I'm using example code generated by AI. When I used egui_plot I had no cc error.
Here is the full AI generated example code
use macroquad::prelude::*;
use egui_macroquad;
use std::env;
use std::path::PathBuf;
use std::ffi::CString;
//use cc;
//use macroquad::ui::widgets::Window;
use egui::{Context, RichText, Window};
unsafe {
extern "C" {

     fn c_function_name(x: i32) -> i32; // Replace with your C function
     //fn c_function_name();
 }  }

#[macroquad::main("egui with macroquad")]
async fn main() {
unsafe {
let result = c_function_name(5); // Call your C function
// Use the result in your Macroquad code
}
let mut ctx = Context::default();
loop {
clear_background(WHITE);

    // Process keys, mouse, etc. (your normal game logic)

    // Call egui_macroquad::ui to create and interact with the egui UI
    egui_macroquad::ui(|egui_ctx| {
       // egui_macroquad::Window::new("My UI").show(egui_ctx, |ui| {
       egui::Window::new("My UI").open(&mut true).show(&ctx, |ui| {         
        //Window::new("My UI").show(egui_ctx, |ui| {        
            ui.label("This is an egui window!");
        });
    });

    // Draw things before egui (your normal Macroquad drawing)

    // Call egui_macroquad::draw to render the egui UI
    egui_macroquad::draw();
    /*unsafe {
         let result = c_function_name(10);
         println!("Result from C: {}", result);
     }  */

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions