3.3.1 Implementing dispinterfaces in Lua
The Automation binding has a C++ class called tLuaDispatch that implements a generic IDispatch interface. The implementation of this class translates the method calls and property accesses done on the objects of this class to Lua calls and table accesses. So, one may implement a dispinterface entirely in Lua, provided it has a type library describing it. This type library may be a stand-alone one (referenced by its location on the file system) or may be associated with some registered component. In this case, it may be referenced by the ProgID of the component.
The C++ objects of this class can be used in any place where an IDispatch or IUnknown interface is expected. LuaCOM takes care of these conversion. Follows a sample implementation of a dispinterface in Lua.
-- Creates and fills the Lua table that will implement the -- COM interface events_table = {} function events_table:AfterUpdate() print("AfterUpdate called!") end -- Here we implement the interface DCalendarEvents, which is part -- of the Microsoft(R) Calendar object, whose ProgID is MSCAL.Calendar events_obj = luacom.ImplInterface( events_table, "MSCAL.Calendar", "DCalendarEvents") -- Checks for errors -- if events_obj == nil then print("Implementation failed") exit(1) end -- Tests the interface: this must generate a call to the events:AfterUpdate -- defined above -- events_obj:AfterUpdate()
If the interface to be implemented is described in a stand-alone
type library, the method ImplInterfaceFromTypelib
must be used instead:
-- Creates and fills the Lua table that will implement the -- Automation interface hello_table = {} function hello:Hello() print("Hello World!") end -- Here we implement the interface IHello -- hello_obj = luacom.ImplInterfaceFromTypelib("hello.tlb","IHello") -- Checks for errors -- if hello_obj == nil then print("Implementation failed") os.exit(1) end -- Tests the interface -- hello_obj:Hello()
Both methods return a LuaCOM object, whose corresponding
IDispatch interface is implemented by the supplied table. This
LuaCOM object can be passed as an argument to COM methods who
expect a dispinterface or to LuaCOM API methods (like
addConnection
).
One can also use the NewObject
method, which is best suited
to the situation where one needs to create a complete component in
Lua and wants to export it, so that it can be accessed through COM
by any running application.
Next: 3.3.2 Using Methods and Up: 3.3 Automation binding Previous: 3.3 Automation binding Contents Fabio Mascarenhas de Queiroz 2005-01-07