v / examples / call_v_from_python / test.py
26 lines · 20 sloc · 942 bytes · cc92dbc8a51a4528fb54aa05b03c18366f7f4505
Raw
1from ctypes import *
2import math, os
3
4## Load the V shared library:
5so_file="./test.so"
6if os.name=="nt":
7 so_file="./test.dll"
8lib = CDLL(so_file)
9
10## Pass an integer to a V function, and receiving back an integer:
11print("lib.square(10) result is", lib.square(10))
12assert lib.square(10) == 100, "Cannot validate V square()."
13
14## Pass a floating point number to a V function:
15lib.sqrt_of_sum_of_squares.restype = c_double
16assert 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()."
17
18## Passing a V string to a V function, and receiving back a V string:
19class VString(Structure):
20 _fields_ = [("str", c_char_p), ("len", c_int)]
21
22lib.process_v_string.argtypes = [VString]
23lib.process_v_string.restype = VString
24
25assert lib.process_v_string(VString(b'World', 5)).str == b'v World v'
26print('Hello', str(lib.process_v_string(VString(b'World', 5)).str, 'utf-8'))
27