From cc92dbc8a51a4528fb54aa05b03c18366f7f4505 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Mon, 3 Jun 2024 19:26:17 +0300 Subject: [PATCH] examples: show how to create and pass a V string to a V function, and then get back a V string in Python --- examples/call_v_from_python/test.py | 14 ++++++++++++++ examples/call_v_from_python/test.v | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/examples/call_v_from_python/test.py b/examples/call_v_from_python/test.py index e85620cca39d82..018335275f1b59 100644 --- a/examples/call_v_from_python/test.py +++ b/examples/call_v_from_python/test.py @@ -1,12 +1,26 @@ from ctypes import * import math, os +## Load the V shared library: so_file="./test.so" if os.name=="nt": so_file="./test.dll" lib = CDLL(so_file) + +## Pass an integer to a V function, and receiving back an integer: print("lib.square(10) result is", lib.square(10)) assert lib.square(10) == 100, "Cannot validate V square()." +## Pass a floating point number to a V function: lib.sqrt_of_sum_of_squares.restype = c_double assert lib.sqrt_of_sum_of_squares(c_double(1.1), c_double(2.2)) == math.sqrt(1.1*1.1 + 2.2*2.2), "Cannot validate V sqrt_of_sum_of_squares()." + +## Passing a V string to a V function, and receiving back a V string: +class VString(Structure): + _fields_ = [("str", c_char_p), ("len", c_int)] + +lib.process_v_string.argtypes = [VString] +lib.process_v_string.restype = VString + +assert lib.process_v_string(VString(b'World', 5)).str == b'v World v' +print('Hello', str(lib.process_v_string(VString(b'World', 5)).str, 'utf-8')) diff --git a/examples/call_v_from_python/test.v b/examples/call_v_from_python/test.v index 250791edace2c2..adc0d30f1b18b2 100644 --- a/examples/call_v_from_python/test.v +++ b/examples/call_v_from_python/test.v @@ -1,5 +1,6 @@ module test +// Note: compile this with `v -d no_backtrace -shared test.v` import math @[export: 'square'] @@ -11,3 +12,9 @@ fn square(i int) int { fn sqrt_of_sum_of_squares(x f64, y f64) f64 { return math.sqrt(x * x + y * y) } + +// you do not have to use the same name in the export attribute +@[export: 'process_v_string'] +fn work(s string) string { + return 'v ${s} v' +}