DiCE API nvidia_logo_transpbg.gif Up
Example for Starting and Shutting Down the DiCE API
[Next] [Up]

This example accesses the main DiCE interface, queries the API version, and then starts and shuts down the DiCE API. See the Getting Started Section for a description of how the example programs can be compiled.

New Topics

  • Naming conventions.
  • Main include files.
  • Main API access point.
  • Interfaces and handles.
  • Starting and shutting down the DiCE API.

Detailed Description

Naming conventions


The DiCE library is written in C++. It uses the mi and mi::neuraylib namespaces for its own identifiers, or the MI_NEURAYLIB_ prefix for macros.

Multiple words are concatenated with _ to form identifiers. Function names are all lower case, while types and classes start with one initial upper-case letter.

Main include files


The include file mi/dice.h provides all the functionality of the DiCE API.

Main API access point


The mi_factory() function is the only public access point to all algorithms and data structures in the API (see Library Design for an explanation why.) The factory function tries to access the DiCE API. If the access succeeds, it returns a pointer to an instance of the main mi::neuraylib::INeuray interface. The mi_factory() function may be called only once per process.

Before you are able to call the mi_factory() function, you need to load the DiCE DSO and to locate the factory function. The convenience function load_and_get_ineuray() abstracts these platform-dependent steps.

Note that it is not required to use load_and_get_ineuray(). In particular in larger setups you might want to write your own code to load the DiCE DSO and to locate the factory function. In such cases, you call mi_factory() directly. For simplicity, the examples will use the convenience function load_and_get_ineuray() instead of mi_factory().

Interfaces and handles


Except for trivial classes, such as the math vector class, all classes in the DiCE API are implemented using interfaces. See Library Design for an explanation. Interfaces are created and destroyed by the DiCE API. They implement reference counting for life-time control and cheap copying operations. Interface names start with an I prefix.

Whenever you do not need an interface any longer, you have to release it by calling its release() method. Omitting such calls leads to memory leaks. To simplify your life we provide a simple handle class mi::base::Handle. This handle class maintains a pointer semantic while supporting reference counting for interface pointers. For example, the -> operator acts on the underlying interface pointer, which means that you can use a handle to a particular interface pointer in a way very similar to the interface pointer itself. The destructor calls release() on the interface pointer, copy constructor and assignment operator take care of retaining and releasing the interface pointer as necessary.

Note that the handle class has two different constructors to deal with ownership of the interface pointer. See the mi::base::Handle documentation for details.

Note that it is also possible to use other handle class implementations, e.g., std::tr1::shared_ptr<T> (or boost::shared_ptr<T>). In case you prefer to use such handle classes, you have to ensure that their destructor calls the release() method of the interface pointer. This can be achieved by passing an appropriate argument as second parameter, e.g.,

std::tr1::shared_ptr<T> p (mi_factory(), std::mem_fun (&T::release));
mi::base::IInterface * mi_factory(const mi::base::Uuid &iid)
Unique public access point to the DiCE API.

Starting and shutting down the DiCE API


The mi::neuraylib::INeuray interface is used to start and shut down the DiCE API. The API can only be used after it has been started (and before it has been shut down). Startup does not happen during the mi_factory() call because you might want to configure the behavior of the API, which has to happen before startup (see Example for Configuration of the DiCE API for details).

The status of the API can be queried using the mi::neuraylib::INeuray::get_status() method.

Finally, you have to shut down the DiCE API. At this point, you should have released all interface pointers except the pointer to the main mi::neuraylib::INeuray interface. If you are using the handle class, make sure that all handles have gone out of scope.

Example Source

Source Code Location: examples/example_shared.h

/******************************************************************************
* Copyright 2023 NVIDIA Corporation. All rights reserved.
*****************************************************************************/
// examples/example_shared.h
//
// Code shared by all examples
#ifndef EXAMPLE_SHARED_H
#define EXAMPLE_SHARED_H
#include <cstdio>
#include <cstdlib>
#include <mi/dice.h>
#ifdef MI_PLATFORM_WINDOWS
#include <mi/base/miwindows.h>
#else
#include <dlfcn.h>
#include <unistd.h>
#endif
#include "authentication.h"
// Pointer to the DSO handle. Cached here for unload().
void* g_dso_handle = 0;
// Ensures that the console with the log messages does not close immediately. On Windows, the user
// is asked to press enter. On other platforms, nothing is done as the examples are most likely
// started from the console anyway.
void keep_console_open() {
#ifdef MI_PLATFORM_WINDOWS
if( IsDebuggerPresent()) {
fprintf( stderr, "Press enter to continue . . . \n");
fgetc( stdin);
}
#endif // MI_PLATFORM_WINDOWS
}
// Helper macro. Checks whether the expression is true and if not prints a message and exits.
#define check_success( expr) \
do { \
if( !(expr)) { \
fprintf( stderr, "Error in file %s, line %u: \"%s\".\n", __FILE__, __LINE__, #expr); \
keep_console_open(); \
exit( EXIT_FAILURE); \
} \
} while( false)
// Helper function similar to check_success(), but specifically for the result of
// #mi::neuraylib::INeuray::start().
void check_start_success( mi::Sint32 result)
{
if( result == 0)
return;
fprintf( stderr, "mi::neuraylib::INeuray::start() failed with return code %d.\n", result);
fprintf( stderr, "Typical failure reasons are related to authentication, see the\n");
fprintf( stderr, "documentation of this method for details.\n");
keep_console_open();
exit( EXIT_FAILURE);
}
// printf() format specifier for arguments of type LPTSTR (Windows only).
#ifdef MI_PLATFORM_WINDOWS
#ifdef UNICODE
#define FMT_LPTSTR "%ls"
#else // UNICODE
#define FMT_LPTSTR "%s"
#endif // UNICODE
#endif // MI_PLATFORM_WINDOWS
// Loads the DiCE library and calls the main factory function.
//
// This convenience function loads the DiCE DSO, locates and calls the #mi_factory()
// function. It returns an instance of the main #mi::neuraylib::INeuray interface. It also
// supplies a authentication key (only needed by some variants of the DiCE library).
// The function may be called only once.
//
// \param filename The file name of the DSO. It is feasible to pass \c NULL, which uses a
// built-in default value.
// \return A pointer to an instance of the main #mi::neuraylib::INeuray interface
mi::neuraylib::INeuray* load_and_get_ineuray( const char* filename = 0)
{
#ifdef MI_PLATFORM_WINDOWS
if( !filename)
filename = "libdice.dll";
void* handle = LoadLibraryA((LPSTR) filename);
if( !handle) {
LPTSTR buffer = 0;
LPTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, 0))
message = buffer;
fprintf( stderr, "Failed to load library (%u): " FMT_LPTSTR, error_code, message);
if( buffer)
LocalFree( buffer);
return 0;
}
void* symbol = GetProcAddress((HMODULE) handle, "mi_factory");
if( !symbol) {
LPTSTR buffer = 0;
LPTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, 0))
message = buffer;
fprintf( stderr, "GetProcAddress error (%u): " FMT_LPTSTR, error_code, message);
if( buffer)
LocalFree( buffer);
return 0;
}
#else // MI_PLATFORM_WINDOWS
if( !filename)
filename = "libdice.so";
void* handle = dlopen( filename, RTLD_LAZY);
if( !handle) {
fprintf( stderr, "%s\n", dlerror());
return 0;
}
void* symbol = dlsym( handle, "mi_factory");
if( !symbol) {
fprintf( stderr, "%s\n", dlerror());
return 0;
}
#endif // MI_PLATFORM_WINDOWS
g_dso_handle = handle;
mi::neuraylib::INeuray* neuray = mi::neuraylib::mi_factory<mi::neuraylib::INeuray>( symbol);
if( !neuray)
{
mi::neuraylib::mi_factory<mi::neuraylib::IVersion>( symbol));
if( !version)
fprintf( stderr, "Error: Incompatible library.\n");
else
fprintf( stderr, "Error: Library version %s does not match header version %s.\n",
version->get_product_version(), MI_NEURAYLIB_DICE_PRODUCT_VERSION_STRING);
return 0;
}
check_success( authenticate( neuray) == 0);
return neuray;
}
// Unloads the DiCE library.
bool unload()
{
#ifdef MI_PLATFORM_WINDOWS
int result = FreeLibrary( (HMODULE)g_dso_handle);
if( result == 0) {
LPTSTR buffer = 0;
LPTSTR message = TEXT("unknown failure");
DWORD error_code = GetLastError();
if( FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, 0, error_code,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, 0))
message = buffer;
fprintf( stderr, "Failed to unload library (%u): " FMT_LPTSTR, error_code, message);
if( buffer)
LocalFree( buffer);
return false;
}
return true;
#else
int result = dlclose( g_dso_handle);
if( result != 0) {
printf( "%s\n", dlerror());
return false;
}
return true;
#endif
}
// Sleep the indicated number of seconds.
void sleep_seconds( mi::Float32 seconds)
{
#ifdef MI_PLATFORM_WINDOWS
Sleep( static_cast<DWORD>( seconds * 1000));
#else
usleep( static_cast<useconds_t>( seconds * 1000000));
#endif
}
// Map snprintf to _snprintf on Windows older than VisualStudio 2015
#if defined(MI_PLATFORM_WINDOWS) && (_MSC_VER < 1900)
#define snprintf _snprintf
#endif
#endif // MI_EXAMPLE_SHARED_H
Handle class template for interfaces, automatizing the lifetime control via reference counting.
Definition: handle.h:113
This is an object representing the DiCE library.
Definition: ineuray.h:44
DiCE API.
float Float32
32-bit float.
Definition: types.h:51
signed int Sint32
32-bit signed integer.
Definition: types.h:46
#define MI_NEURAYLIB_DICE_PRODUCT_VERSION_STRING
DiCE product version number in a string representation, such as "2016".
Definition: dice.h:52

Source Code Location: examples/example_start_shutdown.cpp

/******************************************************************************
* Copyright 2023 NVIDIA Corporation. All rights reserved.
*****************************************************************************/
// examples/example_start_shutdown.cpp
//
// Obtain an INeuray interface, start DiCE and shut it down.
#include <mi/dice.h>
// Include code shared by all examples.
#include "example_shared.h"
// The main function initializes the DiCE library, starts it, and shuts it down after waiting for
// user input.
int main( int /*argc*/, char* /*argv*/[])
{
// Get the INeuray interface in a suitable smart pointer.
mi::base::Handle<mi::neuraylib::INeuray> neuray( load_and_get_ineuray());
if( !neuray.is_valid_interface()) {
fprintf( stderr, "Error: The DiCE library failed to load and to provide "
"the mi::neuraylib::INeuray interface for the API version %d.\n",
keep_console_open();
return EXIT_FAILURE;
}
// Access API and library version numbers.
mi::Uint32 interface_version = neuray->get_interface_version();
const char* version = neuray->get_version();
fprintf( stderr, "DiCE header API interface version = %d\n", MI_NEURAYLIB_API_VERSION);
fprintf( stderr, "DiCE header API version = %s\n",
fprintf( stderr, "DiCE library API interface version = %d\n", interface_version);
fprintf( stderr, "DiCE library build version string = \"%s\".\n", version);
// configuration settings go here, none in this example
// After all configurations, DiCE is started. A return code of 0 implies success. The start can
// be blocking or non-blocking. Here the blocking mode is used so that you know that DiCE is up
// and running after the function call. You can use a non-blocking call to do other tasks in
// parallel and check with
//
// neuray->get_status() == mi::neuraylib::INeuray::STARTED
//
// if startup is completed.
mi::Sint32 result = neuray->start( true);
check_start_success( result);
// interactions with the DiCE library go here, none in this example.
// Shutting down in blocking mode. Again, a return code of 0 indicates success.
check_success( neuray->shutdown( true) == 0);
neuray = 0;
// Unload the DiCE library
check_success( unload());
keep_console_open();
return EXIT_SUCCESS;
}
unsigned int Uint32
32-bit unsigned integer.
Definition: types.h:49
#define MI_NEURAYLIB_API_VERSION
ABI version number.
Definition: version.h:32
#define MI_NEURAYLIB_VERSION_QUALIFIED_STRING
DiCE API major and minor version number and qualifier in a string representation, such as "2....
Definition: version.h:69
[Next] [Up]