2009-04-13 32 views
2

我在使用Ruby设置FFI结构时遇到了一些初学者问题。我想要做的是通过在FFI :: Struct对象设置一个字符串属性传递一个指向C字符串:Ruby Noobie:如何在FFI 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>' 

所以我不知道该从哪里出发。

另外,如果你知道任何关于这个问题的好的文档或教程,请留下回复!到目前为止,我发现在Project Kenai 上的wiki文档非常有用,但越多越好!

谢谢!

我试图将字符串数据成员声明为[:焦炭,5]但是,让另一个错误:

jukebox.rb:44:in `put': put not supported for FFI::StructLayoutBuilder::ArrayField_Signed8_3 (ArgumentError) 
    from jukebox.rb:44:in `[]=' 
    from jukebox.rb:44:in `<main> 

有一个很好的建议,尝试内存指针类型,我会尝试,今天下班后。

+1

我喜欢你的标题。伟大的韵律! – jjnguy 2009-04-13 20:45:16

回答

0

FFI自动拒绝设置字符串。尝试对其进行更改:字符串:CHAR_ARRAY,在this page提到:

:char_array - used ONLY in a struct layout where struct has a C-style string (char []) as a member

如果不工作,你将不得不使用:指针,并将其转换回字符串。它没有很好的记录,但MemoryPointer有一个bunch of available functions,如write_string,应该有所帮助。

+0

感谢您的信息,它确实让我朝着正确的方向发展。我已经尝试过:char数组,它似乎不能在struct声明中工作,请参阅编辑的问题。 – mikelong 2009-04-14 05:08:39

1

因此,感谢来自Pesto的回答(接受),我找到了解决方案。如果缓冲区中有一个零字节,则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) 
相关问题