Write a small function to push 10 unique values from 0 to 50 into a queue.
function void push_unique(ref bit [7:0] array[$]);
for (int i = 0; i < 10; i++) begin
int num;
std::randomize(num) with { num inside {[0:50]};
!(num inside {array});
};
array.push_back(num);
end
endfunction
A static cast is a SystemVerilog feature that converts an expression from one data type to another, using the single-quote (') operator. This is different from $cast — covered in SystemVerilog Cast Dynamic — which performs its check at run time and can fail gracefully. A static cast's type compatibility is checked once, at compile time, with no run-time validity check at all. The conversion itself, though, still runs at simulation time whenever its operand isn't a constant — casting a variable or signal costs the same as any other expression; it's only the type-checking that's free.
9 min read | Intermediate Level
What You'll Learn
- What a static cast is, and how it differs from
$cast - How casting a string to an integer packs its trailing bytes into a fixed-width value
- The real distinction between real-to-integer truncation and bit-width truncation
- Why a static cast doesn't perform any run-time validity checking
Syntax
'(value or variable or expression)
The type being cast to comes immediately before the single quote — for example, int'(expr) — and the value or expression being cast must be in parentheses.
Static Cast vs $cast
Static cast (type'(expr)) | $cast | |
|---|---|---|
| When checked | Compile time | Run time |
| On an invalid conversion | Silently produces whatever the reinterpreted bits happen to mean — no error | Runtime error (as a task) or returns 0 (as a function) |
| Performance impact | No run-time cost for the type check; the conversion itself still runs whenever its operand isn't a constant | Run-time overhead for both the validity check and the conversion |
Casting a String to an Integer
A string can be cast to a compatible data type like int:
module tb;
initial begin
$display("data=%0d", int'("Hello World"));
end
endmodule
Output
xcelium> run data=1869769828 xmsim: *W,RNQUIE: Simulation is complete.
This number isn't arbitrary. int is 4 bytes wide, and "Hello World" is 11 characters — too many to fit. Only the last 4 characters, "orld", actually get packed into the result, each character's ASCII code becoming one byte: o=0x6F, r=0x72, l=0x6C, d=0x64, giving 0x6F726C64 — which is exactly 1869769828 in decimal.
Quick Check
Q: What would int'("World") produce?
Show Answer
The exact same value, 1869769828. "World" is 5 characters, so only its last 4 — "orld" — get packed, which happens to be identical to the last 4 characters of "Hello World".
Real-to-Integer Truncation
Casting a computed real expression to int drops the fractional part entirely:
module tb;
initial begin
$display("data=%0.3f", int'(3.4 + 2 * 1.5));
end
endmodule
Output
xcelium> run data=6.000 xmsim: *W,RNQUIE: Simulation is complete.
3.4 + 2 * 1.5 evaluates to 6.4, and int'(...) truncates that down to the integer 6, discarding the fractional part rather than rounding it.
module tb;
int data;
initial begin
data = int'(3.145);
$display("data=%0.3f", data);
end
endmodule
Output
xcelium> run data=3.000 xmsim: *W,RNQUIE: Simulation is complete.
int'(3.145) similarly truncates to 3. It's worth being precise about what's happening here: this is real-to-integer truncation — dropping the fractional part of a real number — which is a different mechanism from truncating the bits of a wide integer value, covered next.
Bit-Width Truncation (Narrowing a Vector)
Casting a wider integer value into a narrower type keeps only its least significant bits, discarding everything above that width:
module tb;
bit [31:0] wide = 32'hDEAD_BEEF;
bit [15:0] narrow;
initial begin
narrow = 16'(wide);
$display ("narrow = 0x%0h", narrow);
end
endmodule
This prints narrow = 0xbeef — only the lower 16 bits of 32'hDEAD_BEEF survive the cast; the upper half (DEAD) is simply discarded, with no warning or error of any kind.
This is the property the previous section's int'(3.145) example doesn't actually demonstrate. Truncating a real number's fractional part and truncating a wide integer's most significant bits are two genuinely different mechanisms — both fall under "truncation" loosely, but they don't behave the same way, and it's easy to conflate the two.
Quick Check
Q: Using the same 32'hDEAD_BEEF value, what would 8'(wide) produce?
Show Answer
0xEF — just the single lowest byte. Narrowing to 8 bits keeps only the lowest 8 bits of the original 32-bit value, discarding the rest.
Other Properties
- Static cast enforces type safety at compile time — it won't allow casting between genuinely incompatible data types (like two unrelated class handles with no relationship to each other).
- It's applicable to both variables and full expressions, not just simple values.
- It's generally described as preserving the signedness of the source value, though this depends on the specific source and target types involved — when in doubt, verify the actual result for your specific case rather than assuming.
Where Is Static Cast Used?
Static cast is commonly used when deliberately packing or narrowing a value into a fixed-width field — preparing data for a DPI call with a specific expected width, or extracting a specific byte or field from a wider computed value — situations where the conversion is known to be intentional and correct, so $cast's run-time checking overhead isn't needed.
Common Beginner Mistakes
Mistake #1: Confusing static cast with $cast
A static cast performs zero run-time checking — an invalid or lossy conversion succeeds silently, with no error and no way to detect failure. Why? If there's a real chance a cast might not be meaningful (like recovering a specific class type from a base handle), $cast is the right tool, since it can actually report failure; a static cast simply reinterprets bits and moves on.
Mistake #2: Assuming int'(3.145) demonstrates bit-width truncation
As explained above, this is real-to-integer truncation — dropping a fractional part — not the same mechanism as narrowing a wide integer value down to fewer bits. Why? The two are easy to conflate since both are casually called "truncation," but they behave differently and apply to different situations.
Mistake #3: Mixing a %f format specifier with a non-real value
%f is meant for real-valued arguments, yet several examples in this article pass an already-cast integer to it. Why? While some simulators display a reasonable-looking result anyway, this isn't guaranteed portable behavior across every tool — match your format specifier to your actual argument's type to avoid relying on simulator-specific leniency.
Mistake #4: Assuming a lossy static cast is always harmless
As the bit-width truncation example shows, a static cast that discards real data does so completely silently. Why? There's no warning when a narrowing cast throws away meaningful bits — it's on the code's author to be certain the narrower type is actually wide enough for the values that will realistically flow through it.
Practice Exercise
Challenge: Predict a String-to-Int Cast
Using the same last-4-characters rule demonstrated in this article, predict the result of int'("Verilog").
Hint
"Verilog" is 7 characters — identify the last 4, convert each to its ASCII hex value, and pack them together the same way "Hello World" packed down to "orld".
Solution
1768714087. The last 4 characters of "Verilog" are "ilog": i=0x69, l=0x6C, o=0x6F, g=0x67, packed as 0x696C6F67 — which is 1768714087 in decimal.
Summary
In this tutorial, you learned:
- A static cast (
type'(expr)) converts a value's type at compile time, with no run-time validity checking — unlike$cast - Casting a string to an integer type packs only as many trailing characters as fit the target width, each becoming one byte
- Real-to-integer casting truncates the fractional part; bit-width narrowing truncates the most significant bits of a wide integer value — two genuinely different mechanisms, both loosely called "truncation"
- A lossy or narrowing static cast succeeds silently, with no warning that data was discarded
- Static cast is best used when a conversion is already known to be correct and intentional, since it has no way to report failure the way
$castcan
SystemVerilog DPI (Direct Programming Interface) lets you interface between SystemVerilog and foreign programming languages such as C, C++, and SystemC. It's an easy and efficient way to connect existing code — usually written in C or C++ — without needing to learn PLI or VPI at all.
9 min read | Intermediate Level
What You'll Learn
- What DPI is, and the problem it solves compared to PLI/VPI
- The import declaration syntax, for calling a C function from SystemVerilog
- The export declaration syntax, for calling a SystemVerilog function from C
- What it actually takes to compile and link C code into a simulation, beyond just the DPI declaration
- How basic SystemVerilog and C data types map to each other across the DPI boundary
Import Declarations
Methods implemented in a foreign language can be called from SystemVerilog once declared with an import declaration. Imported subroutines can have zero or more input, output, or inout arguments, and can return void or a result:
import "DPI-C" function void init();
import "DPI-C" function int sum(int a, b);
Export Declarations
Methods implemented in SystemVerilog can be called from foreign code once specified in an export declaration:
export "DPI-C" function int randomize(int range_a, range_b);
A Complete Example
The SystemVerilog side declares and calls the imported C function:
module tb_top;
// Import the function called "system_init" implemented in C code
import "DPI-C" function void system_init();
initial begin
$display ("[%0t] Call C method", $time);
system_init();
end
endmodule
And the C side implements it:
#include "stdio.h"
#include "stdlib.h"
extern "C" void system_init() {
printf("Start system initialization ...\n");
}
extern "C" is a C++-only linkage specifier — a genuine C compiler doesn't recognize this syntax at all and would fail on this exact line. This file is only valid as written if it's actually compiled with a C++ compiler (like g++), despite using plain C headers and looking like a C file. If you're compiling this with a real C compiler instead, drop extern "C" entirely — a plain C function already has the linkage DPI expects, with no special keyword needed.
Declaring the import in SystemVerilog isn't enough on its own — the C (or C++) source still has to be compiled and linked into the simulation. Most simulators expect this as a separate compile step alongside the SystemVerilog compile, for example:
# Example (tool and flag names vary by simulator):
gcc -c system_init.c -o system_init.o
xrun testbench.sv system_init.o
Once both pieces are compiled and linked together, running the simulation produces output from both languages, in the order they actually execute:
[0] Call C method
Start system initialization ...
The first line is SystemVerilog's own $display; the second is the C function's printf, executing the moment system_init() is called from the initial block.
Quick Check
Q: If the C source file were never compiled and linked into the simulation at all, what would happen when system_init() is called?
Show Answer
A link-time (or elaboration-time) error — the SystemVerilog side declares that system_init() exists and what its signature looks like, but the actual implementation has to come from somewhere. Without compiling and linking the C code, there's nothing behind that declaration.
Passing Arguments Between SystemVerilog and C
Extending the sum import declared earlier into a full working example — the SystemVerilog side:
import "DPI-C" function int sum(int a, int b);
module tb;
initial begin
$display ("sum(3,4) = %0d", sum(3,4));
end
endmodule
And the matching C implementation:
int sum(int a, int b) {
return a + b;
}
Calling sum(3,4) from the initial block crosses into the C function, computes 3 + 4, and returns 7 back into SystemVerilog — from the testbench's point of view, this is no different from calling any other function, even though the actual computation happened in compiled C code.
Common SystemVerilog-to-C Type Mapping
DPI defines a standard mapping between simple SystemVerilog and C types:
| SystemVerilog Type | C Type |
|---|---|
| byte | char |
| shortint | short int |
| int | int |
| longint | long long |
| real | double |
| shortreal | float |
| string | const char* |
Multi-bit bit and logic vectors don't map onto ordinary C integer types this simply — they use DPI's own special vector types (svBitVecVal, svLogicVecVal) on the C side to correctly represent packed 4-state or 2-state vectors of arbitrary width. Stick to the simple scalar types in the table above until you specifically need to pass a wide vector across the boundary.
Where Is DPI Used?
DPI is commonly used to call into an existing C or C++ reference model — a bit-accurate golden model of an algorithm, for instance — directly from a scoreboard, instead of reimplementing that same logic in SystemVerilog. It's also a practical way to reuse legacy C testbench utility code without a full rewrite.
Common Beginner Mistakes
Mistake #1: Mismatching extern "C" with the actual compiler used
As flagged above, extern "C" only means something to a C++ compiler. Why? Using it in a file compiled as plain C is a syntax error; omitting it in a file compiled as C++ can cause a link-time "undefined reference" error instead, since C++ name-mangles function names by default unless told not to.
Mistake #2: Forgetting the C code still needs to be compiled and linked
An import "DPI-C" declaration only tells SystemVerilog that a function exists somewhere — it doesn't make the implementation appear. Why? The actual C or C++ source still has to be compiled separately and linked into the simulation, using whatever mechanism your specific simulator provides for that.
Mistake #3: Mismatching argument types between the two languages
The SystemVerilog import declaration's argument types have to correspond correctly to the actual C function's parameter types. Why? A mismatch isn't always caught cleanly at compile time, and can silently produce corrupted or misinterpreted data crossing the language boundary instead of a clear error.
Mistake #4: Assuming an imported DPI function can consume simulation time
A plain import "DPI-C" function follows the same rule as any other SystemVerilog function — no time-consuming behavior. Why? If the C side genuinely needs to model something that takes simulation time, DPI separately supports importing a task instead of a function for that purpose — a different declaration with different rules, not something a plain function import can do.
Practice Exercise
Challenge: Add a subtract() Function
Following the same pattern as sum, declare and implement a DPI-imported subtract(int a, int b) function that returns a - b.
Hint
You need two matching pieces, just like sum: the import "DPI-C" declaration on the SystemVerilog side, and the actual function body on the C side.
Solution
import "DPI-C" function int subtract(int a, int b);
module tb;
initial begin
$display ("subtract(10,4) = %0d", subtract(10,4));
end
endmodule
int subtract(int a, int b) {
return a - b;
}
subtract(10,4) returns 6, computed entirely on the C side and handed back to SystemVerilog — exactly the same calling pattern as sum, just with different arithmetic inside the C function.
Summary
In this tutorial, you learned:
- DPI lets SystemVerilog call into (and be called from) C, C++, or SystemC code, without needing PLI or VPI
- An
import "DPI-C"declaration makes a foreign function callable from SystemVerilog; anexport "DPI-C"declaration makes a SystemVerilog function callable from foreign code - Declaring an import isn't enough on its own — the foreign source still has to be compiled and linked into the simulation separately
extern "C"only means something in C++ code, and using or omitting it incorrectly for the actual compiler in use causes a compile or link error- Simple scalar types map directly between SystemVerilog and C (like
inttoint,bytetochar); wide vectors need DPI's own special vector types instead
What is a SystemVerilog interface ?
SystemVerilog interfaces are a way to create structured hierarchical connections between modules and blocks in a design. They provide a way to bundle signals and functionality into reusable components, which can be easily instantiated and connected in a design.
- Modular design: Interfaces provide a modular approach to design, making it easier to create and reuse building blocks in a system.
- Encapsulation: They help in encapsulating the functionality and signals inside a module or block, making it easier to understand and maintain.
- Configurability: Interfaces can be parameterized, allowing for easy configurability and scalability.
Read more on SystemVerilog Interface.
Is it possible to override existing constraints?
Yes, it's possible to override existing constraints in SystemVerilog using inline constraints or inheritance.
class ABC;
rand bit [3:0] data;
constraint c_data { data inside {[5:10]}; }
endclass
module tb;
initial begin
ABC abc = new;
// Use inline constraint to override with new value
// Note that this should not contradict the hard constraints in ABC
abc.randomize() with { data == 8; };
end
endmodule
Quiz
No quiz questions available for this article.