#[tokio::DllMain]
#[no_mangle]
extern "system" async fn DllMain(_: *const u8, _: u32, _: *const u8) -> u32{
let resp = reqwest::get("http://httpbin.org/ip")
.await?
.json::<HashMap<String, String>>()
.await?;
println!("{:#?}", resp);
Ok(())
}
Where are you getting that tokio::DllMain
attribute from? I can't see anything in the docs for its Windows build mentioning that.
The tokio::main
attribute is just shorthand for creating a new runtime and blocking until the function body completes.
From the attribute's examples, this snippet
#[tokio::main(flavor = "current_thread")]
async fn main() {
println!("Hello world");
}
expands to
fn main() {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("Hello world");
})
}
I mean
#[no_mangle]
extern "system" fn DllMain(_: *const u8, _: u32, _: *const u8) -> u32{
resolve_http().await // how to call await in Dllmain
0
}
#[tokio::main]
async fn resolve_http() -> reqwest::Result<()>{
let resp = reqwest::get("http://httpbin.org/ip")
.await?
.json::<HashMap<String, String>>()
.await?;
println!("{:#?}", resp);
Ok(())
}
The same as in any other sync function - by explicitly creating the runtime and calling block_on
or equivalent. An example for Tokio was provided above.
You can't use .await
in any function that isn't a Rust's native async fn
or async {}
block. Functions that use .await
don't directly execute the code, but rather they transform it to be a state machine encoded in a Future
struct. DllMain
is supposed to be a function, not a Future
struct, so this can't work.
However, you can wait for Future
s in a regular function, in a blocking way (non-async) by using a Tokio runtime handle and its block_on
method.
tokio::main
macro doesn't do much. It's basically this:
tokio::runtime::Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async { function body goes here })
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.