Subject:
[ruby-ffi] Getting a pointer from a String
From:
candlerb
Date:
5/6/11 8:02 AM
To:
ruby-ffi

Take the following code:

    class Msghdr < FFI::Struct
      layout :name, :pointer,
        :namelen, :socklen_t,
        :iov, :pointer,
        :iovlen, :size_t,
        :control, :pointer,
        :controllen, :socklen_t,
        :flags, :int
    end

    class IOVec < FFI::Struct
      layout :base, :pointer,
        :len, :size_t
    end

    def sendmsg(mesg)
      data = FFI::MemoryPointer.new(mesg.bytesize, 1, false)
      data.put_bytes(0, mesg)

      iov = IOVec.new
      iov[:base] = data
      iov[:len] = mesg.bytesize

      header = Msghdr.new
      header[:iov] = iov
      header[:iovlen] = 1

This works. However, I would like to avoid copying the incoming String
object into a new MemoryPointer. Is this possible?

If I write:

    iov[:base] = mesg

then I get an error saying that mesg is not a pointer.

I found method MemoryPointer.from_string, but that just does a copy as
well.

Have I missed something?

Thanks,

Brian.