Struct pointer and struct both seems ok to time functions that receive struct pointer, is this normal?

  • From: "Nan Xiang" <280145668@xxxxxx>
  • To: "luajit" <luajit@xxxxxxxxxxxxx>
  • Date: Sun, 25 Sep 2016 11:06:12 +0800

Environment: Cloud9 Ubuntu 14.04. Luajit 2.1.0-beta2Code below shows you can 
pass either struct pointer or struct as second parameter of `ffi.C.gmtime_r`. 
So, is this a bug? which way should I take?
```
local ffi = require("ffi")
ffi.cdef[[
typedef uint32_t time_t;
struct tm {
  int second;        /* Seconds. [0-60] (1 leap second) */
  int minute;        /* Minutes. [0-59] */
  int hour;          /* Hours.   [0-23] */
  int day;           /* Day.     [1-31] */
  int month;         /* Month.   [0-11] */
  int year;          /* Year - 1900.  */
  int wday;          /* Day of week. [0-6] */
  int yday;          /* Days in year.[0-365] */
  int isdst;         /* DST.     [-1/0/1]*/
  long int gmtoff;       /* Seconds east of UTC.  */
  const char* zone;      /* Timezone abbreviation.  */
};
struct tm* gmtime_r   (const time_t*, struct tm*);
struct tm* localtime_r(const time_t*, struct tm*);
char*      asctime_r  (const struct tm*, char*);
time_t     mktime     (struct tm*);
]]


local function strfmt(tm)
  return string.format('%d-%s-%s %s:%s:%s', 
      tm.year+1900, 
      tm.month+1, 
      tm.day, 
      tm.hour, 
      tm.minute, 
      tm.second)
end
local seconds = 1474728477
local seconds_ptr = ffi.new("time_t[1]", seconds)


-- pass as struct
local tm = ffi.new("struct tm")
ffi.C.gmtime_r(seconds_ptr, tm)
print(strfmt(tm))


-- pass as struct pointer
local tm_ptr = ffi.new("struct tm[1]")
ffi.C.gmtime_r(seconds_ptr, tm_ptr)
print(strfmt(tm_ptr[0]))
```
Will get:
```
pronan:~/workspace (master) $ luajit test.lua
2016-9-24 14:47:57
2016-9-24 14:47:57

```

Other related posts:

  • » Struct pointer and struct both seems ok to time functions that receive struct pointer, is this normal? - Nan Xiang