DEV Community

Cover image for How to create and use DLL's on VLang

Posted on

How to create and use DLL's on VLang

Hi, this is going to be a very compact post as this will only cover a simple example of creating and using dll's and some limitations I have found when calling dll's from V.

First we will have an example dll called "example.dll" this file will expose the hello_world function which will print Hello World to standard output.

The code to generate our example DLL is as follows:

// file: example.v

@[export: 'hello_world']
fn hello_world() {
    println("Hello World")
Enter fullscreen mode Exit fullscreen mode

Now we run it:
$ v ./example.v -shared -o example.dll.

Now we need to write the following in our V program:

Note that you have to replace <absolute path to the DLL> with your own path

// file: main.v

import dl.loader;

type DLLFunc = fn ()

fn main() {

    mut dl_loader := loader.get_or_create_dynamic_lib_loader(
        key: "example",
        paths: ["<absolute path to the DLL>"]

    defer {

    dll_func := dl_loader.get_sym("hello_world")!

    f_hello_world := DLLFunc(dll_func);


Enter fullscreen mode Exit fullscreen mode

It is really important to make the DLLFunc type match the dll function signature to make the compiler happy and not get any unexpected problems.

If we have done everything well and we run
$ v run ./main.v then
we will see our 'Hello World'.

Now if we want to pass some args it is as simple as adding an argument to the hello_world function on example.v, compile it into a shared library, then add the argument in our local signature type DLLFunc and it will work 👍!

The only bad thing I have found when working with DLLs in Vlang is the lack of flexibility if you want to work with different generic DLLs, because you need to have a strict type definition for the DLL functions signature. But it is very easy, fast and perfect if you already know how your DLL is at compile time.

Also, thanks to the efforts of the VLang team for the language, it has a lot of simple and interesting features I love ♥.

Top comments (0)