回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>tl;dr</p>
<p>这适用于GNU版本的libc(还没有尝试过uclibc)</p>
<pre><code>from ctypes import *
libc = CDLL('libc.so.6')
class uts_struct(Structure):
_fields_ = [ ('sysname', c_char * 65),
('nodename', c_char * 65),
('release', c_char * 65),
('version', c_char * 65),
('machine', c_char * 65),
('domain', c_char * 65) ]
gnar = uts_struct()
libc.uname(byref(gnar))
print gnar.nodename
</code></pre>
<hr/>
<h2>原岗位</h2>
<p>以下代码段错误;我不确定我做错了什么。在</p>
^{pr2}$
<p>这样做是一样的:</p>
<pre><code>from ctypes import *
libc = CDLL('libc.so.6')
class uts_struct(Structure):
_fields_ = [ ('sysname', c_char_p),
('nodename', c_char_p),
('release', c_char_p),
('version', c_char_p),
('machine', c_char_p) ]
utsname = uts_struct()
utsname_pointer = pointer(utsname)
libc.uname(utsname_pointer)
print utsname.sysname
</code></pre>
<p>我一定是搞砸了一些基本的东西。。。在</p>
<p>(我知道<code>os.uname()</code>,这只是一个理解的练习,我失败了)</p>
<p>我在这里引用了uname手册:<a href="http://www.cl.cam.ac.uk/cgi-bin/manpage?2+uname" rel="nofollow noreferrer">http://www.cl.cam.ac.uk/cgi-bin/manpage?2+uname</a></p>
<p>我做错什么了?在</p>
<hr/>
<p><strong>编辑:</strong></p>
<p>多亏了<a href="https://stackoverflow.com/users/768469/nemo">Nemo</a>我能够得到数据</p>
<pre><code>>>> from ctypes import *
>>> libc = CDLL('libc.so.6')
>>> gnar = create_string_buffer(512)
>>> libc.uname(byref(gnar))
0
>>> print gnar.value
Linux
>>>
</code></pre>
<p>但是,我假设我只得到'Linux',因为这些项是空分隔的,调节器字符串也是。有没有办法读过空值?在</p>
<hr/>
<p><strong>编辑2:</strong></p>
<p>根据Nemos的评论,我试过这个-这不起作用,但我认为这可能是朝着正确方向迈出的一步。。。错误:</p>
<pre><code>Traceback (most recent call last):
File "gnar.py", line 18, in <module>
utsname = uts_struct(gnar)
TypeError: incompatible types, c_char_Array_512 instance instead of c_char_p instance
</code></pre>
<p>这是不可能的吗?在</p>
<pre><code>from ctypes import *
libc = CDLL('libc.so.6')
class uts_struct(Structure):
_fields_ = [ ('sysname', c_char_p),
('nodename', c_char_p),
('release', c_char_p),
('version', c_char_p),
('machine', c_char_p) ]
gnar = create_string_buffer(512)
libc.uname(byref(gnar))
utsname = uts_struct(gnar)
</code></pre>
<hr/>
<p><strong>Edit3:</strong>(我要找有史以来最长的帖子。。。=P)</p>
<pre><code>from ctypes import *
libc = CDLL('libc.so.6')
class uts_struct(Structure):
_fields_ = [ ('sysname', c_char * 65),
('nodename', c_char * 65),
('release', c_char * 65),
('version', c_char * 65),
('machine', c_char * 65) ]
gnar = uts_struct()
libc.uname(byref(gnar))
print gnar.machine
</code></pre>
<p>但是,它在打印值后会分离错误。。。在</p>
<hr/>
<p><strong>最终编辑:</strong></p>
<p>下面的工作-我当然使用的是GNU版本的libc。(在Ubuntu机器上的im)所以添加域字段就可以停止segfault。事后看是有道理的。:)</p>
<pre><code>from ctypes import *
libc = CDLL('libc.so.6')
class uts_struct(Structure):
_fields_ = [ ('sysname', c_char * 65),
('nodename', c_char * 65),
('release', c_char * 65),
('version', c_char * 65),
('machine', c_char * 65),
('domain', c_char * 65) ]
gnar = uts_struct()
libc.uname(byref(gnar))
print gnar.nodename
</code></pre>