平台调用F#回调函数 [英] Platform Invoke F# callback functions

查看:69
本文介绍了平台调用F#回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Raspberry Pi 2(ARM 7和单声道)上使用F#.我目前正在尝试使用用C编写的WiringPi库.我已经成功地设法通过P/Invoke使用了某些功能.

I am using F# on a Raspberry Pi 2 (ARM 7 & thus mono). I am currently trying to use the WiringPi library, written in C. I have successfully managed to use some of the functions using P/Invoke.

现在,我正在尝试使用中断(请参见 http://wiringpi.com/参考/优先级中断和线程/),但此功能让我感到困惑,并带有以下C签名

Now I am trying to use interrupts (see http://wiringpi.com/reference/priority-interrupts-and-threads/) but I am stumped by this function with the following C signature

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

已翻译(请参见 https://github.com. com/danriches/WiringPi.Net/blob/master/WiringPi/WrapperClass.cs )进入这样的C#库

Which has been translated (see https://github.com/danriches/WiringPi.Net/blob/master/WiringPi/WrapperClass.cs) by Daniel Riches into a C# library like this

//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#中已保留)

How on earth would I do this in F#? I guess DllImport line looks like this ("method" is reserved in F#)

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

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

What does the type definition for ISRCallback look like?

注意:这不仅是一个"函数指针,而且是一个带有无效参数的无效指针.

Note: this is not just "a" function pointer but a void one, with void arguments.

推荐答案

委托定义如下所示:

type ISRCallback = delegate of unit -> unit

平台调用签名将如下所示:

And the platform invoke signature would look like this:

[<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中的委托必须进行垃圾收集.开发人员有责任确保在您的本机库不再需要函数回调之前,委托不会超出范围".

You should keep in mind that delegates in .NET are subject to garbage collection. It is the responsibility of the developer to ensure that the delegate doesn't "go out of scope" until your native library no longer needs the function callback.

这篇关于平台调用F#回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆