Skip to content

Python Integration

v2rayroot edited this page Jun 14, 2026 · 1 revision

Python Integration

import ctypes
import json

lib = ctypes.CDLL("./xray-linux-amd64.so")

lib.FreeCString.argtypes = [ctypes.c_void_p]
lib.FreeCString.restype = None

for name in ("GetStatus", "GetVersionInfo", "Stop"):
    getattr(lib, name).restype = ctypes.c_void_p

lib.ValidateConfig.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
lib.ValidateConfig.restype = ctypes.c_void_p
lib.Start.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
lib.Start.restype = ctypes.c_void_p


def take(pointer):
    if not pointer:
        return None
    try:
        return ctypes.string_at(pointer).decode("utf-8")
    finally:
        lib.FreeCString(pointer)


print(json.loads(take(lib.GetVersionInfo())))

config = b'{"inbounds":[],"outbounds":[{"protocol":"freedom","tag":"Proxy"}]}'
validation = json.loads(take(lib.ValidateConfig(config, b"{}")))
if "error" in validation:
    raise RuntimeError(validation["error"])

error = take(lib.Start(config, b"{}"))
if error is not None:
    raise RuntimeError(error)

try:
    print(take(lib.GetStatus()))
finally:
    warning = take(lib.Stop())
    if warning:
        print(warning)

Use c_void_p for returned strings so ownership can be returned explicitly. Do not use c_char_p as the return type for owned native strings.

Clone this wiki locally