How to pass Haskell data through C FFI as an opaque data type?

I am trying to transfer some data through the C library, which does not read or modify this data.

foreign import ccall "lua.h lua_pushlightuserdata"
  c_lua_pushlightuserdata :: LuaState -> Ptr a -> IO ()

foreign import ccall "lua.h lua_touserdata"
  c_lua_touserdata :: LuaState -> CInt -> IO (Ptr a)

data MyData =
  MyData
  { dataIds = TVar [Int]
  , dataSomethingElse = [String]
  }

calledFromRunLuaState :: LuaState -> IO ()
calledFromRunLuaState luaState = do
  dataPtr <- c_lua_touserdata luaState (-1)
  myData <- dataFromPtr dataPtr
  doSomethingWith myData

main = do
  luaState <- Lua.newstate
  ids <- atomically $ newTVar []
  c_lua_pushlightuserdata luaState (dataToPtr (MyData ids []))
  runLuaState luaState

I am trying to figure out how to determine dataFromPtrand dataToPtr.

+4
source share
1 answer

, StablePtr. dataFromPtr newStablePtr, deRefStablePtr dataToPtr. , deRefStablePtr IO, . , , :

foreign import ccall "lua.h lua_pushlightuserdata"
  c_lua_pushlightuserdata :: LuaState -> StablePtr MyData -> IO ()

lua_touserdata.

, newStablePtr, . , - , freeStablePtr.

+4

Source: https://habr.com/ru/post/1656368/


All Articles