> ## Documentation Index
> Fetch the complete documentation index at: https://docs.phones.farm/llms.txt
> Use this file to discover all available pages before exploring further.

# C# Runtime

> High-performance C# / .NET SDK integration and native runtime interop for high-throughput device control.

## 1.Overview

> [!NOTE]
>
> 💡 Unlimited Possibilities
>
> If you're familiar with C#, you can use this interface to build **any low-level functionality and high-performance algorithms**. Whether it's system-level operations or calling third-party DLL libraries!

### Use Cases

#### Scenarios Suitable for C# Runtime:

* 🧮 **Algorithm Computation** - Execute compute-intensive algorithms (such as image processing, data analysis)
* 📦 **Third-party Library Integration** - Call existing .NET libraries (such as OpenCV、YOLO operations, etc.)

### Ready to Use

#### 🔧 Powerful Ecosystem

* **Access .NET Class Libraries** - Can use the entire .NET Framework/Core class library
* **NuGet Package Support** - Can reference and use third-party libraries from NuGet

#### ⚡ High-Performance Hybrid Programming

* **Best Practice Combination** - Can leverage C# to handle compute-intensive tasks
* **In-Process Calling** - C# code is compiled before running, with extremely low call overhead
* **Async Support** - Full support for async/await, fully utilizing asynchronous performance advantages

## 2.Register Code

### Compile and Register C# Code

The `compileCsharp` interface is used to compile C# source code and return a unique function ID (`funid`) for subsequent calls.

### Endpoint Description

#### Endpoint Type

```
compileCsharp
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `code` | string | ✅ | C# source code string |
| `refs` | string\[] | ❌ | Array of managed DLL file paths |

#### Response Payload

Returns a string type `funid` (function ID), used for subsequent calls to this function via the `executeCsharp` interface.

### Basic Usage

#### Simple Example

```
// Compile and register a simple C# function
const funid = await apiInvoke("compileCsharp", {
    code: `
        using System;
        using System.Collections.Generic;
        using System.Runtime.InteropServices;
        using System.Threading.Tasks;
        using OpenCvSharp;
        
        // Load unmanaged DLL
        public static class User32
        {
            [DllImport("user32.dll")]
            public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
        }

        public class Startup
        {
            public async Task<object> Invoke(dynamic args)
            {
                // Get parameters
                byte[] screenShotImage = (byte[])args.screenshot;
                int inta = (int)args.inta;
                float floatb = (float)args.floatb;

                User32.MessageBox(IntPtr.Zero, "OpenCvSharp and user32 are loaded", "Notice", 0);
                //......

                return inta + floatb;
            }
        }
    `,
    // Only managed DLL files are allowed here
    refs: ["D:\\opencv\\OpenCvSharp.dll"]
})

console.log('funid', funid)
// Output: Function ID: abc123def456...
```

### Notes

#### ⚠️ Important Limitations

1. **Managed DLL Limitation**
   * The `refs` parameter can only reference **managed DLLs** (.NET assemblies)
   * For unmanaged DLLs, use `DllImport`
2. **Fixed Class and Method Names**
   * Class name must be `Startup`
   * Method name must be `Invoke`
   * Signature must be `public async Task<object> Invoke(dynamic args)`
3. **Namespace References**
   * Must explicitly reference required namespaces (e.g., `using System;`)
   * Does not automatically reference all namespaces

### Compilation Error Handling

If compilation fails, the interface will throw an exception.

### Next Steps

After compilation, use the returned `funid` to call the function:

See Execute C# Function to learn how to call compiled functions.

## 3.Execute Code

### Execute C# Function

The `executeCsharp` interface is used to execute C# functions that have been compiled and registered through `compileCsharp`.

⏱️ Cold Start Time

First execution will have **50-200 milliseconds** of cold start time, subsequent calls have no overhead.

### Endpoint Description

#### Endpoint Type

```
executeCsharp
```

#### Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `funid` | string | ✅ | Function ID (returned by compileCsharp) |
| `args` | object | ❌ | Parameter object passed to C# function |

#### Response Payload

Returns the execution result of the C# function, type depends on the C# function's return value.

### Basic Usage

#### Complete Flow Example

```
// 1. Function ID obtained from compilation
const funid = 'XXXXX';

// 2. Execute function
const result = await apiInvoke("executeCsharp", {
    funid: funid,
    args: {
        inta: 10,
        floatb: 18.8,
        // Can reference magic parameter variables
        screenshot: "$.screenshot('deviceId')"
    }
});

console.log('Execution result:', result);
```

### Magic Parameter Variables

iClick provides special magic variables that can dynamically obtain system data during calls. Magic variables start with `$.` and are automatically parsed to actual data before execution.

#### Available Magic Variables

| Magic Variable | Description | Return Type | Usage Example |
| - | - | - | - |
| `$.screenshot(deviceId)` | Get real-time screenshot of specified device | `byte[]` | `"$.screenshot('P72578581E07')"` |

### Notes

#### ⚠️ Important Notes

1. **Magic Variable Usage Rules**
   * Magic variables must be passed as **strings** (e.g., `"$.screenshot('id')"`)
   * Magic variables are automatically parsed to actual data before execution
2. **funid Validity**
   * funid is valid during application runtime
   * Needs to be recompiled after application restart
3. **Parameter Type Matching**
   * Parameter types must match types in C#
   * Pay attention to numeric type precision issues
4. **Memory Management**
   * Promptly release unmanaged resources in C#, release related resources after task processing
   * Fatal code defects may cause iClick to crash


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.