Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Haskell
Wiki community
Recent changes
Random page
HaskellWiki
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Ru/FFI Introduction
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Краткий пример == В [[FFICookBook]] приведено много хороших примеров, но вот один из базовых: <haskell> {-# INCLUDE <math.h> #-} {-# LANGUAGE ForeignFunctionInterface #-} module FfiExample where import Foreign.C -- get the C types -- pure function -- "unsafe" means it's slightly faster but can't callback to haskell foreign import ccall unsafe "sin" c_sin :: CDouble -> CDouble sin :: Double -> Double sin d = realToFrac (c_sin (realToFrac d)) </haskell> Обратите внимание, что в документации к FFI рекомендуется, записывать имя заголовочного файла между двойными кавычками, вот так <haskell> foreign import ccall unsafe "math.h sin" c_sin :: CDouble -> CDouble </haskell> А вот в GHC документации говорится, что "Правильный Способ" -- использование директив компилятора (может быть по причинам технического характера?), поэтому, обычно, большинство импортов состоит из нескольких заголовочных файлов C (.h), которые прописывают один раз перед кодом на Haskell в самом начале файла. Следует отметить, что типы C отличаются от типов Haskell, поэтому вы должны импортировать их из модуля Foreign.C. Notice also that, as usual in haskell, you have to explicitly convert to and from haskell types. Using c_<name_of_c_function> for the raw C function is just my convention. The haskell report only guarantees that Int has 30 bits of signed precision, so converting CInt to Int is not safe! On the other hand, many classes have instances for Int and Integer but not CInt, so it's generally more convenient to convert from the C types. To convert, I suppose you could either write a checkedFromIntegral function if you're sure it's small or just use Integer. For details on impure functions, pointers to objects, etc., see the cookbook.
Summary:
Please note that all contributions to HaskellWiki are considered to be released under simple permissive license (see
HaskellWiki:Copyrights
for details). If you don't want your writing to be edited mercilessly and redistributed at will, then don't submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
DO NOT SUBMIT COPYRIGHTED WORK WITHOUT PERMISSION!
Cancel
Editing help
(opens in new window)
Toggle limited content width