Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What about those callbacks? #50

Open
shepmaster opened this issue Jun 29, 2017 · 1 comment
Open

What about those callbacks? #50

shepmaster opened this issue Jun 29, 2017 · 1 comment

Comments

@shepmaster
Copy link
Owner

shepmaster commented Jun 29, 2017

How can a callback be passed to C when it might run on another thread?

How can user data be passed? Is there a magic way to pass userdata when there's no userdata parameter?

@shepmaster shepmaster changed the title Callbacks What about those callbacks? Jun 29, 2017
@OptimisticPeach
Copy link

OptimisticPeach commented Feb 26, 2019

Hmm, perhaps your code must be written with Arc<Mutex<T>>s beforehand and passed a pointer to Fn* dynamic object which would then be passed back to rust which could successfully call it? Or perhaps creating a special struct which inherits Fn* and could provide a ffi to the other language.
For the first idea:

#[no_mangle]
pub extern fn get_callback() -> *mut Fn()->() {
    || {println!("HI")}
}
#[no_mangle]
pub extern fn run_callback(cback: *mut Fn() -> ()) -> bool {
    (*cback)();
    true
}

and for the other side, I'm not familiar with c externs so I'll post a c# example:

using System;
using System.Runtime.InteropServices;

class FnFFI
{
    bool initialized;
    (UIntPtr, UIntPtr) callback;
    public FnFFI() {
         callback = GetCallBack();
         initialized = true;
    }
    public void Run() {
        if this.initialized {
            if !RunCallBack(this.callback) {
                throw new Exception("This shouldn't happen :/");
            }
        }
    }
    [DllImport("fn_ffi", EntryPoint="get_callback")]
    public static extern (UIntPtr, UIntPtr) GetCallBack();
    
    [DllImport("fn_ffi", EntryPoint="run_callback")]
    public static extern bool RunCallBack((UIntPtr, UIntPtr) callback);

    static public void Main()
    {
        FnFFI callback = new FnFFI();
        callback.Run();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants