unsafePerformIO和FFI库初始化 [英] unsafePerformIO and FFI library initialization

查看:144
本文介绍了unsafePerformIO和FFI库初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建C中的FFI模块一个库,希望1时,非重入函数被调用之前别的是。此调用是幂等的,但有状态,所以我只是把它在每一个哈斯克尔电话。但它是缓慢的,由于非重入可能会导致冲突。

I'm creating an FFI module to a library in C which wants a 1-time, non-reentrant function to be called before anything else is. This call is idempotent, but stateful, so I could just call it in every Haskell call. But it's slow and due to non-reentrancy it could cause conflicts.

因此​​,这是使用unsafePerformIO正确的时间?我可以在一个不安全的IOREF或无功换一个布尔值,使忽略后续调用(调用其中全球,隐IOREF状态是假)幂等这些初始化调用。

So is this the right time to use unsafePerformIO? I could wrap a Bool in an unsafe IORef or MVar to make these initialization calls idempotent by ignoring subsequent calls (calls where the global, hidden IORef state is False).

如果没有,什么是做到这一点的正确方法?

If not, what is the right way to do this?

推荐答案

我preFER初始化一次,并提供伪造的令牌你已经初始化的机器证明的方法。

I prefer the approach of initializing once and providing an unforgeable token as evidence that you have initialized the machine.

所以,你的证据是:

data Token = Token

您导出抽象。

那么你的初始化函数可以返回这方面的证据。

Then your initialization function can return this evidence.

init :: IO Token

现在,你需要证明了这一点传递给你的API:

Now, you need to pass that proof to your API:

bar  :: Token -> IO Int
bar !tok = c_call_bar

等。

您现在可以换这个东西了一个单子,或者一些高阶的初始化环境,使之更清洁,但是这是基本的想法。用户自定义各种你能来,这样就可以不通过未定义作为证据。

You can now wrap this stuff up with a monad , or some higher order initialization environment to make it cleaner, but that's the basic idea. With user-defined kinds you could make it so that you can't pass undefined as evidence.

与初始化使用隐藏状态的C库的问题是,你最终要么不能够并行访问图书馆,或有问题ghci中,混合编译和字节code,有两个不同版本的C的库加载(这将失败,并链接错误)。

The problem with initializing C libraries using hidden state is that you end up either not being able to parallelize access to the library, or having problems in GHCi, mixing compiled and bytecode, with two different versions of the C library loaded (which will fail with a linker error).

这篇关于unsafePerformIO和FFI库初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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