【问题标题】:Using struct timeval in Python在 Python 中使用 struct timeval
【发布时间】:2012-04-23 21:04:20
【问题描述】:

我有一个包含结构的 C 程序

struct S{
           int x;
           struct timeval t;
 };

还有一个函数

int func(struct S s1, struct S s2)

我需要从我的 python 程序中调用这个函数。 我用的是ctypes。Python上的并行结构

import ctypes
from ctypes import *
class S(Structure):
        _fields_ = [("x",c_int),
                     ("t", ?)]

现在,我的问题是我将在 ? place 以及与之相关的任何依赖项。 提前致谢。

【问题讨论】:

  • 我的建议 - 它适用于许多平台,但并非适用于所有平台,请确保操作系统目标和测试是什么。

标签: python ctypes timeval


【解决方案1】:

在您平台的 C 包含文件中找到 struct timeval 的定义(互联网建议使用 sys/time.h),然后将其转码为 ctypes 结构。

在我的平台上,struct timeval

struct timeval {
  long tv_sec;
  long tv_usec;
};

(我想无论如何这是标准),所以

class timeval(Structure):
    _fields_ = [("tv_sec", c_long), ("tv_usec", c_long)]

class S(Structure):
    _fields_ = [("x",c_int), ("t", timeval)]

可能符合要求。

【讨论】:

  • 还有一个问题.. 这种结构(时间值)是否会因平台而异?
  • 是的,它会改变,例如 64 位的 NetBSD 6.0(或更高版本)。小心。
  • @tiago-peczenyj 处理这些平台依赖项的聪明方法是什么?
【解决方案2】:

没有任何进一步的信息,它将是timeval的定义:

class timeval(Structure):
    _fields_ = [("tv_sec",c_long),
                 ("tv_usec", c_long)]

class S(Structure):
    _fields_ = [("x",c_int),
                 ("t", timeval)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-02
    • 2012-09-25
    • 1970-01-01
    • 2017-09-01
    • 2021-05-03
    • 2013-06-28
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多