遇到一些问题初学者设定红宝石的FFI结构。我想要做的是通过在FFI ::设置一个字符串属性将指针传递给C字符串Struct对象:

class SpSessionConfig < FFI::Struct
  layout :api_version,          :int,
           :cache_location,       :string,
           :settings_location,    :string,
           :application_key,      :pointer,
           :application_key_size, :int,
           :user_agent,           :string,
           :sp_session_callbacks, :pointer,
           :user_data,            :pointer 
  end
end


sessionConf = SpotifyLibrary::SpSessionConfig.new() 
puts sessionConf # => '#<SpotifyLibrary::SpSessionConfig:0x9acc00c>'

sessionConf[:api_version] = 1
puts "Api Version: #{sessionConf[:api_version]}"

myTempDir = "tmp"
sessionConf[:cache_location] = myTempDir # !Error!

但是当我运行的代码我得到这个错误:

jukebox.rb:44:in `[]=': Cannot set :string fields (ArgumentError)
from jukebox.rb:44:in `<main>'

所以,我真的不知道从哪里何去何从。

另外,如果你知道有关这个问题的好documtation或教程,请留下一个回应!到目前为止,我已经找到noreferrer"> Kenai项目上

有帮助吗?

解决方案

FFI自动拒绝设置字符串。尝试对其进行更改:字符串:CHAR_ARRAY,在此页面

  

:CHAR_ARRAY - 在一个结构布局,其中结构有一个C风格串仅用于(CHAR [])作为成员

如果不工作,你将不得不使用:指针,并将其转换回字符串。这不是有据可查的,但MemoryPointer拥有的一堆可用功能的的,如write_string,应该帮助。

其他提示

因此由于从香草答案(接受)我已经找到了解决方案。早期write_string返回如果在缓冲器中的零字节(如下:C-串语义)。下面是代码的人谁可能碰上这个问题在未来。

# Open my application key file and store it in a byte array
appkeyfile = File.read("spotify_appkey.key")

# get the number of bytes in the key
bytecount = appkeyfile.unpack("C*").size

# create a pointer to memory and write the file to it
appkeypointer = FFI::MemoryPointer.new(:char, bytecount)
appkeypointer.put_bytes(0, appkeyfile, 0, bytecount)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top