1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

dl: add a complete tested shared library generation/usage example

This commit is contained in:
Delyan Angelov
2020-12-15 18:22:07 +02:00
parent e3a1756b11
commit 3a9034a0d0
6 changed files with 105 additions and 23 deletions

View File

@@ -1,11 +1,10 @@
module dl
#include <dlfcn.h>
pub const (
rtld_now = C.RTLD_NOW
rtld_now = C.RTLD_NOW
rtld_lazy = C.RTLD_LAZY
dl_ext = '.so'
dl_ext = get_shared_library_extension()
)
fn C.dlopen(filename charptr, flags int) voidptr
@@ -28,3 +27,14 @@ pub fn close(handle voidptr) bool {
pub fn sym(handle voidptr, symbol string) voidptr {
return C.dlsym(handle, symbol.str)
}
pub fn get_shared_library_extension() string {
mut res := '.so'
$if macos {
res = '.dylib'
}
$if windows {
res = '.dll'
}
return res
}

10
vlib/dl/example/library.v Normal file
View File

@@ -0,0 +1,10 @@
module library
[export: 'add_1']
pub fn add_1(x int, y int) int {
return my_private_function(x + y)
}
fn my_private_function(x int) int {
return 1 + x
}

17
vlib/dl/example/use.v Normal file
View File

@@ -0,0 +1,17 @@
module main
import os
import dl
type FNAdder = fn (int, int) int
fn main() {
library_file_path := os.join_path(os.getwd(), 'library${dl.dl_ext}')
handle := dl.open(library_file_path, dl.rtld_lazy)
eprintln('handle: ${ptr_str(handle)}')
mut f := &FNAdder(0)
f = dl.sym(handle, 'add_1')
eprintln('f: ${ptr_str(f)}')
res := f(1, 2)
eprintln('res: $res')
}

View File

@@ -0,0 +1,52 @@
module main
import os
import dl
const (
vexe = os.real_path(os.getenv('VEXE'))
cfolder = os.dir(@FILE)
so_ext = dl.dl_ext
library_file_name = os.join_path(cfolder, 'library$so_ext')
)
fn test_vexe() {
eprintln('vexe: $vexe')
assert vexe != ''
eprintln('os.executable: ' + os.executable())
eprintln('@FILE: ' + @FILE)
eprintln('cfolder: $cfolder')
eprintln('so_ext: $so_ext')
eprintln('library_file_name: $library_file_name')
}
fn test_can_compile_library() {
os.chdir(cfolder)
os.rm(library_file_name)
res := v_compile('-d no_backtrace -o library -shared library.v')
eprintln('res: $res')
assert os.is_file(library_file_name)
}
fn test_can_compile_main_program() {
os.chdir(cfolder)
assert os.is_file(library_file_name)
result := v_compile('run use.v')
eprintln('result: $result')
assert result.output.contains('res: 4')
os.rm(library_file_name)
}
fn v_compile(vopts string) os.Result {
cmd := '"$vexe" -showcc $vopts'
eprintln('>>> v_compile cmd: $cmd')
res := os.exec(cmd) or { panic(err) }
eprintln('>>> v_compile res: $res')
// assert res.exit_code == 0
$if !windows {
os.system('dir $cfolder -a -l')
} $else {
os.system('dir $cfolder /a')
}
return res
}