平台调用 F# 回调函数

2024-04-18

我在 Raspberry Pi 2(ARM 7 和单声道)上使用 F#。我目前正在尝试使用用 C 编写的 WiringPi 库。我已经成功地使用 P/Invoke 来使用一些函数。

现在我尝试使用中断(参见http://wiringpi.com/reference/priority-interrupts-and-threads/ http://wiringpi.com/reference/priority-interrupts-and-threads/)但我被这个具有以下 C 签名的函数难住了

int wiringPiISR (int pin, int edgeType,  void (*function)(void));

已翻译(参见https://github.com/danriches/WiringPi.Net/blob/master/WiringPi/WrapperClass.cs https://github.com/danriches/WiringPi.Net/blob/master/WiringPi/WrapperClass.cs) 由 Daniel Riches 编写成这样的 C# 库

//This is the C# equivelant to "void (*function)(void))" required by wiringPi to define a callback method 
public delegate void ISRCallback(); 

[DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")] 
public static extern int wiringPiISR(int pin, int mode, ISRCallback method); 

我到底该如何在 F# 中做到这一点?我猜 DllImport 行看起来像这样(“方法”在 F# 中保留)

[<DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")>] 
  extern int wiringPiISR(int pin, int mode, ISRCallback callBack);

ISRCallback 的类型定义是什么样的?

注意:这不仅仅是“一个”函数指针,而且是一个带有 void 参数的 void 函数指针。


委托定义看起来像这样:

type ISRCallback = delegate of unit -> unit

平台调用签名如下所示:

[<DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")>] 
extern int wiringPiISR(int pin, int mode, [<MarshalAs(UnmanagedType.FunctionPtr)>]ISRCallback callBack);

该函数的用法示例:

let callback : ISRCallback = ISRCallback(fun () -> (*do something interesting here*) ())
let result = wiringPiISR(1, 1, callback)

您应该记住,.NET 中的委托会受到垃圾回收的影响。开发人员有责任确保委托不会“超出范围”,直到您的本机库不再需要函数回调。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

平台调用 F# 回调函数 的相关文章

随机推荐