Boscop / web-view

Rust bindings for webview, a tiny cross-platform library to render web-based GUIs for desktop applications
MIT License
1.92k stars 175 forks source link

Problem storing WebView instances globally #331

Closed gitgit3 closed 3 months ago

gitgit3 commented 3 months ago

First, I have 30 yrs dev experience (C/C++,Java etc), but I am completely new to Rust. So this is very likely a dumb question but I've been struggling now for over 10 hours.

I currently have 2 WebView windows showing with the references local (on the stack) and in a struct. But I am unable to store the instances of WebView in a global location, either as static, in a struct/Box/Mutex, pretty much any solution I try boils down to the same error: *mut webview_sys::CWebView` cannot be sent between threads safely

I have no desire to use multiple threads, but even trying to use a Mutex.lock() around the instances does not satisfy the compiler.

Is this an issue with CWebView not implementing Send + Sync or is it more likely that my Rust abilities suck ?

I am at a loss. Does anyone have any ideas how to do this?

gitgit3 commented 3 months ago

It appears that CWebView is a C-pointer. I was able to get the code to compile by implementing Send and Sync on both CWebView and WebView. So this partly answers my question. Clearly, I cannot know what is going on behind the scenes in the C-code so marking this pointer as such is not the solution.

Does anyone see any reason why this should not be implemented in WebView ?

It appears that Rust will not allow a global reference to this pointer, although it will allow a local one. This seems absurd. Maybe I should go to a Rust forum and ask further questions.

gitgit3 commented 3 months ago

Turns out I simply needed the 'mut' modifier. Something like this:

pub static mut WV_A_WIN: Option<WebView> = None ; fn main () {
let mut wv = web_view::builder() .title("Test Builder") ...etc WV_A_WIN = Some( wv ); WV_A_WIN.as_mut().unwrap().set_visible( true ); }