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.
Interface Description
Interface Type
compileCsharpParameters
| Parameter | Type | Required | Description |
|---|---|---|---|
code | string | ✅ | C# source code string |
refs | string[] | ❌ | Array of managed DLL file paths |
Return Value
Returns a string type funid (function ID), used for subsequent calls to this function via the executeCsharp interface.
Basic Usage
Simple Example
javascript
// 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
Managed DLL Limitation
- The
refsparameter can only reference managed DLLs (.NET assemblies) - For unmanaged DLLs, use
DllImport
- The
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)
- Class name must be
Namespace References
- Must explicitly reference required namespaces (e.g.,
using System;) - Does not automatically reference all namespaces
- Must explicitly reference required namespaces (e.g.,
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.