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