Giter VIP home page Giter VIP logo

soq-struct-string's Introduction

struct-string

See the corresponding SO question!

Suppose you have a C-struct

typedef struct {
  uint32_t num;
  char*    str;
} MyStruct;

and a function f that does some operation on it. The char* num has to be allocated a sufficient buffer before calling f:

char buf[64];	//somehow you know 64 is enough
MyStruct s = {1, buf};
f(buf);

The question is how to write a Haskell FFI for this kind of C API. Start with

data MyStruct = MyStruct {
    num :: Word32,
    str :: String
} deriving Show

and write a Storable instance. My idea is to allocate 64 bytes at the end which will serve as buffer for the string:

instance Storable MyStruct where
    sizeOf _ = 8{-alignment!-} + sizeOf (nullPtr :: CString) + 64{-buffer-}
    alignment _ = 8

poke has to change the pointer in str to point to the allocated buffer and then the Haskell string has to be copied into it:

    poke p x = do
        pokeByteOff p 0 (num x)
        poke strPtr bufPtr
        withCStringLen (str x) $ \(p',l) -> copyBytes bufPtr p' (l+1) -- +1? not sure
        where strPtr = castPtr $ plusPtr p 8 :: Ptr CString
              bufPtr = castPtr $ plusPtr p 16 :: CString
              

peek is then straightforward:

    peek p = MyStruct 
         <$> peek (castPtr p)
         <*> peekCAString (castPtr $ plusPtr p 16)

soq-struct-string's People

Contributors

mcmayer avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.