[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: FFI metamethods on C struct pointer
- From: Duncan Cross <duncan.cross@...>
- Date: Sat, 11 Jun 2011 17:02:53 +0100
On Sat, Jun 11, 2011 at 4:49 PM, Javier Guerra Giraldez
<javier@guerrag.com> wrote:
> On Sat, Jun 11, 2011 at 9:20 AM, Mike Pall <mikelu-1106@mike.de> wrote:
>>> am i missing something obvious?
>>
>> Well, that should work just fine. How did you define the struct?
>> You realize that each "struct {...}" defines a _unique_ struct,
>> even if it has the same members? Better use a named struct or a
>> typedef everywhere.
>
> that's good news, at least there's some hope that if i bang my head
> hard enough, something should fall off. :-)
>
> yes, i use typedef everywhere, and ffi.typeof() as soon as possible:
>
>
>
> i also tried def
>
>> Maybe posting a simplified excerpt of your code would help.
>> Quite often the problem is solved during that process. :-)
>
> of course, i did some minimal tests that _do_ work, so i then spent
> some hours trying to make it fail.
>
> for example, this works perfectly:
>
>
> local ffi = require "ffi"
>
> ffi.cdef [[
> typedef struct bstr {
> size_t len;
> const char *str;
> } bstr;
> ]]
>
> bstr_t = ffi.typeof ('bstr')
>
> ffi.metatype (bstr_t, {
> __tostring = function (b)
> return ffi.string (b.str, b.len)
> end,
> })
>
> local b = bstr_t(3, 'hi!')
> print (type (b), b)
>
> ===> cdata hi!
>
>
> i guess the main difference is that here i'm using the FFI constructor
> (bstr_t(...)) and not receiving a struct pointer from a C function.
> i'm trying to find some constructor-like function in the stdlib to use
> as example.
>
>
>
> --
> Javier
>
>
The __tostring metamethod seems to be the problem specifically, for example:
local ffi = require 'ffi'
ffi.cdef [[
typedef struct { float x,y,z; } testvector;
]]
ffi.metatype('testvector', {
__index = function(self) return 11; end;
__tostring = function(self) return self.x..','..self.y..','..self.z end;
})
x = ffi.new 'testvector'
print(x.fakefield) --> 11
print(x) --> 0,0,0
x_ptr = ffi.cast('testvector*', x)
print(x_ptr.fakefield) --> 11
print(x_ptr) --> cdata<struct *>
x_array = ffi.new('testvector[11]')
print(x_array[0].fakefield) --> 11
print(x_array[0]) --> cdata<struct &>
By the way, I seem to be having trouble compiling the git head at the
moment on Windows with VC++05 Express, it spits out a lot of errors
starting with:
c:\sdks\luajit\git\luajit-2.0\src\buildvm.h(55) : error C2016: C
requires that a struct or union has at least one member
c:\sdks\luajit\git\luajit-2.0\src\buildvm.h(55) : error C2061: syntax
error : identifier 'int32_t'
c:\sdks\luajit\git\luajit-2.0\src\buildvm.h(58) : error C2059: syntax
error : '}'
(...)
-Duncan