Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Runtime Reflection

(Back to Tutorials)

In this tutorial you will see examples on how to:

  • Load a program's map file via DDL
  • Discover symbols at runtime via DDL

Source Listing for this tutorial

Introduction

While runtime reflection seems like a rather advanced place to get started with DDL, it is in fact the most elementary. As you will see in the course of these Tutorials, all of DDL is a continuous progression of this theme. DDL's capability to load and link binary code at runtime is essentially useless without the ability to reflect upon that code.

1. Create a Host Program

The host program, that is where main() lives, is going to be responsible for loading the in-situ module via DDL. As the name implies, the in-situ module defines the in-place symbol information that is normally thrown out by the compiler.

module reflect;
import ddl.DefaultRegistry;
import mango.io.Stdout;

export void test(){
	Stdout.put("Hello DDL World"c).put(CR);
}

void main(){
    auto registry = new DefaultRegistry();
    auto inSitu = registry.load("reflect.map");
    
    auto testFn = inSitu.getDExport!(void function(),"reflect.test")();
    testFn();
}

Note the 'export' in the function definition above. This is important since nothing else calls test(), and the linker will be inclined to throw it away. While you can prevent this behavior by using the /NOPACKFUNCTIONS linker switch, your executable file will bloat considerably as a result.

3. Compile via Build

To build the reflection sample (reflect.d), simply invoke build using the "-L-map" switch.

build examples/reflect/reflect -L-map

The map switch is important as it instructs the linker to generate a mapfile that is complete, and isn't missing any important details about our program.

4. Try It Out

When build is done, run the sample program:

> reflect
Hello DDL World