Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use from C# a Rust function that has another function as a parameter?

The following example illustrates what I am looking to do. The operation function receives a value and a function as a parameter, then returns the execution of the function. So far everything is perfect. Now I would like to use that function operation in a library to consume in C#.

fn operation(number: i32, f: &dyn Fn(i32) -> i32) -> i32 {
    f(number)
}
fn square(number: i32) -> i32 {
    number * number
}
fn cube(number: i32) -> i32 {
    number * number * number
}

fn test() {// passing a function as parameter, OK :)
    println!("{}", operation(5, &square));
    println!("{}", operation(7, &square));
    println!("{}", operation(3, &cube));
}

// Tried without success :_(
/*
#[no_mangle] 
pub extern "C" c_operation(number: i32, f: &dyn Fn(i32) -> i32) -> *mut i32 {
    unsafe {
     &mut f(number)
    }
}
*/

What should the right signature of the function c_operation?

I think that the following C# code should work when the signature is well defined in the library.

const string RSTLIB = "../../PathOfDLL";

public delegate int Fn(int number);

[DllImport(RSTLIB)] static extern int c_operation(int x, Fn fn);

int Square(int number) => number * number;
int Cube(int number) => number * number * number;

void Test()
{
    Console.WriteLine("{0}", c_operation(5, Square));
    Console.WriteLine("{0}", c_operation(7, Square));
    Console.WriteLine("{0}", c_operation(3, Cube));
}

I appreciate your attention

like image 473
Alexandra Danith Ansley Avatar asked Dec 30 '25 17:12

Alexandra Danith Ansley


1 Answers

For use from C, one way to declare c_operation and define it in terms of operation would be something like:

#[no_mangle]
pub extern "C" fn c_operation(
    number: i32,
    f: unsafe extern "C" fn(i32) -> i32
) -> i32 {
    operation(number, &|n| unsafe { f(n) })
}
like image 190
user4815162342 Avatar answered Jan 02 '26 07:01

user4815162342



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!