Skip to content

CSharp Integration

v2rayroot edited this page Jun 14, 2026 · 1 revision

C# Integration

using System;
using System.Runtime.InteropServices;

internal static class V2RootNative
{
    private const string Library = "xray-windows-amd64.dll";

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr GetStatus();

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr ValidateConfig(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string config,
        [MarshalAs(UnmanagedType.LPUTF8Str)] string options);

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr Start(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string config,
        [MarshalAs(UnmanagedType.LPUTF8Str)] string options);

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr Stop();

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    internal static extern void FreeCString(IntPtr value);

    internal static string? Take(IntPtr pointer)
    {
        if (pointer == IntPtr.Zero) return null;
        try { return Marshal.PtrToStringUTF8(pointer); }
        finally { FreeCString(pointer); }
    }
}

Do not marshal owned return values directly as string; retain the pointer so FreeCString can be called.

Clone this wiki locally