Uno/Cpp/Snippet/Instantiate a Service

From Apache OpenOffice Wiki
< Uno‎ | Cpp
Jump to: navigation, search
using namespace ::rtl;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
    // get service manager of component context
    // ( how the context is bootstrapped, is explained below ).
    Reference < XMultiComponentFactory > rServiceManager = xContext->getServiceManager();
    // create the Pipe service
    Reference< XInterface > r = rServiceManager->createInstanceWithContext(
                  OUString::createFromAscii( "" ), xContext );
    assert( ); // the service must exist
    // ask the XInterface-reference for the XInputStream interface
    Reference< XInputStream > rInputStream( r , UNO_QUERY );
    assert( ); // the service must support XInputStream
    // ask the XInterface-reference for the XOutputStream interface
    Reference< XOutputStream > rOutputStream( r , UNO_QUERY );
    assert( ) // test service must support XOutputStream
    [.... do some calls on the references]
    // each references calls release when it is destructed.
    // The last release destroys the object.

In the first line, an initial component context (factory context) is bootstrapped (see below , how this can be done). The second line retrieves the bootstrapped service manager of the context. The next line creates the service and returns a reference to XInterface (Note: the operator ->() simply returns the unacquired interface pointer). This service supports XInputStream and XOutputStream , the next lines retrieve these interfaces. The used reference constructor (the magic UNO_QUERY is an element of a dummy enum, that allows to have a 2nd constructor which takes an interface reference as an argument) performs a queryInterface on r for the interface (here XInputStream and XOutputStream), the results are stored within the references.

Personal tools