仅供参考,我能得到下面的步骤在Windows下工作...
{-# LANGUAGE ForeignFunctionInterface #-}
module Fibonacci() where
import Data.Word
import Foreign.C.Types
fibs :: [Word32]
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
fibonacci :: Word8 -> Word32
fibonacci n =
if n > 47
then 0
else fibs !! (fromIntegral n)
c_fibonacci :: CUChar -> CUInt
c_fibonacci (CUChar n) = CUInt (fibonacci n)
foreign export ccall c_fibonacci :: CUChar -> CUInt
与
ghc --make -shared Fibonacci.hs
这将产生半打的文件,其中一个是HSdll.dll
编译此。然后我复制到这一个Visual Studio C#项目,并做了以下内容:
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
public sealed class Fibonacci : IDisposable
{
#region DLL imports
[DllImport("HSdll.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern unsafe void hs_init(IntPtr argc, IntPtr argv);
[DllImport("HSdll.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void hs_exit();
[DllImport("HSdll.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 c_fibonacci(byte i);
#endregion
#region Public interface
public Fibonacci()
{
Console.WriteLine("Initialising DLL...");
unsafe { hs_init(IntPtr.Zero, IntPtr.Zero); }
}
public void Dispose()
{
Console.WriteLine("Shutting down DLL...");
unsafe { hs_exit(); }
}
public UInt32 fibonacci(byte i)
{
Console.WriteLine(string.Format("Calling c_fibonacci({0})...", i));
var result = c_fibonacci(i);
Console.WriteLine(string.Format("Result = {0}", result));
return result;
}
#endregion
}
}
的Console.WriteLine()
电话是明显可选。
我还没有尝试过在Mono/Linux下运行它,但它大概是类似的。
总之,获得C++ DLL的难度大致相同。 (即获得类型签名匹配并使编组正确工作是困难的)
我还必须编辑项目设置并选择“允许不安全的代码”。
对于FFI绑定,您将始终有一个计划B,即“用C编写一个薄包装器”。大多数具有任何类型的FFI的语言都可以与C互操作。 –
指针:GHC用户指南的第4.13和8.2章,http://www.haskell.org/haskellwiki/Calling_Haskell_from_C –
看来GHC有一章创建了DLL :http://www.haskell.org/ghc/docs/latest/html/users_guide/win32-dlls.html此部分在GHC的最新版本中也有所变化。 (!) – MathematicalOrchid