Mike Pall wrote: > > Claire Lewis wrote: > > Is there some way to provide my own constructor for a ctype in > > FFI? Specifically for an opaque type that I have a C call to > > create, such as: > > ... > > Well, types don't have user-definable constructors in C, either. > [They do in C++. But C++ support isn't on the horizon, yet.] Understood; partly this is trying to make the interface here a little more Lua like, and partly because I am interfacing to C++ of course (via many tedious stub functions). > In the general case, you'll want access to plain object creation > (if the size is known) or to one of several user-defined > constructors. Now, how do you differentiate those cases? If you > can override the default constructor with your own function, then > how do you create the object inside of that function, if needed? I suppose I had thought overriding it would preclude "simple" creation of the struct, but that's not a very orthogonal solution either. Maybe it would always be possibel to use the string form, ffi.new("struct blah") or somesuch. > I can see the benefit of orthogonality. But then ... the user of > such a type doesn't really need the ctype. They should never > instantiate it themselves. And in fact, they cannot do this for an > incomplete struct, anyway. > > I'd redefine the problem as 'give me a constructor for every type' > as opposed to 'give me a ctype for every type'. Then you can > return either the ctype (which works as a constructor) or an > explicit constructor function. The user of the library doesn't > need to care, they just write 'local o = OpaqueType()'. Well, yes and no. I could definitely see users wanting to have access to ffi.istype(). Say, we might have (opaque) structs representing a Vector and a Matrix; someone wants to write a Lua function (or __mul metatable entry) that can take either; they'll need some mechanism to do so. I could provide my own IsType(), though I can't use the (potentially cdata) constructor as a table key, so that's going to be tedious. There are probably other ffi ctype based functions that would be beneficial too, but that's probably the one that stands out. I understand FFI is a low level API, and perhaps I just need to wrap the whole thing. I just don't want to get any unnecessary inefficiencies, or break effective JIT optimisation by adding too many layers to the code. So this brings me to my current thought for a solution; make everything return a "constructor" that is in fact a table with a __call method to construct, but also contains some ".type" key, for things that need to get the ctype. Thanks, - Claire