Rtti.TVirtualInterface (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the capabilities of the TVirtualInterface class. An implementation of a specific interface (ISpecificInterface) is created at run time with the help of TVirtualInterface. An instance of ISpecificInterface ("virtual interface") is obtained from a TVirtualInterface instance by calling QueryInterface. The TVirtualInterface instance is not destroyed explicitly; it is destroyed automatically when the application ends.

An event is defined so that every interface method call will display its name on the console. This is accomplished by implementing the TVirtualInterfaceInvokeEvent interface (see the TVirtualInterfaceInvokeEventHandler class.)

Code

#include <System.hpp>
#include <Rtti.hpp>

#include <stdio.h>
#include <tchar.h>

// ---------------------------------------------------------------------------

// ISpecificInterface
__interface __declspec(uuid("{281D8B97-397E-430A-895A-9CA4E1F5FB5F}"))
	ISpecificInterface : public IInvokable {
public:
	virtual void __fastcall SpecificProcedure() = 0;
};
typedef System::DelphiInterface<ISpecificInterface>_di_ISpecificInterface;

// OnInvoke event handler
class TVirtualInterfaceInvokeEventHandler
	: public TCppInterfacedObject<TVirtualInterfaceInvokeEvent> {

public:
	void __fastcall Invoke(TRttiMethod* method, DynamicArray<TValue>Args,
		TValue& result) {
		printf("%ls\n", method->ToString().c_str());
	}
};

// ---------------------------------------------------------------------------

int _tmain(int argc, _TCHAR* argv[]) {
	_di_TVirtualInterfaceInvokeEvent invokeEvent =
		static_cast<TVirtualInterfaceInvokeEvent*>
		(new TVirtualInterfaceInvokeEventHandler());

	TVirtualInterface *t =
		new TVirtualInterface(__delphirtti(ISpecificInterface), invokeEvent);
	_di_ISpecificInterface specificInterfaceInstance = 0;

	if (t->QueryInterface(__uuidof(ISpecificInterface),
		&specificInterfaceInstance) == S_OK) {
		specificInterfaceInstance->SpecificProcedure();
	}
	else {
		// Should not happen.
		puts("Interface not supported");
	}

	return 0;
}

Console Output

procedure SpecificProcedure

Uses

See Also