惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
V2EX - 技术
V2EX - 技术
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
Recorded Future
Recorded Future
S
Schneier on Security
I
InfoQ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
The GitHub Blog
The GitHub Blog
S
Security @ Cisco Blogs
O
OpenAI News
W
WeLiveSecurity
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
Simon Willison's Weblog
Simon Willison's Weblog
人人都是产品经理
人人都是产品经理
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
NISL@THU
NISL@THU
T
Tailwind CSS Blog
V
Visual Studio Blog
PCI Perspectives
PCI Perspectives
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
D
DataBreaches.Net
B
Blog RSS Feed
N
News and Events Feed by Topic
N
News and Events Feed by Topic
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
腾讯CDC
Latest news
Latest news
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
V
V2EX
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
Help Net Security
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Writing Node.js Addons with .NET Native AOT: A Complete Guide
Vikrant Baga · 2026-04-29 · via DEV Community

Ever wished you could write Node.js native addons in C# instead of C++? .NET Native AOT makes it possible—and practical.

Writing Node.js Addons with .NET Native AOT


The Problem with Traditional Node.js Addons

If you've ever built a Node.js native addon, you know the pain:

  • C++ required: Even for simple functionality, you need C++ knowledge
  • node-gyp complexity: Build system that's notoriously finicky
  • Python dependency: Requires specific Python versions (often outdated)
  • Cross-platform headaches: Different build configurations per OS

For the Microsoft C# Dev Kit team, these friction points added unnecessary complexity to their development workflow. They needed Windows Registry access from their VS Code extension—but the C++ tooling didn't align with their .NET-centric stack.

The Solution: .NET Native AOT

What if you could write Node.js addons in C#? With .NET Native AOT, you can. The C# Dev Kit team replaced their C++ addon with a C# implementation—and it worked beautifully.

Here's why this approach is groundbreaking:

  1. No Python required - Just the .NET SDK
  2. Modern C# features - Type safety, async/await, LINQ
  3. Cross-platform - Works on Windows, Linux, and macOS
  4. Smaller toolchain - One SDK for everything

How It Works: N-API + Native AOT

The Magic Ingredient: N-API

N-API (Node-API) is a stable, ABI-compatible C API for building Node.js addons. The key insight: N-API doesn't care what language you use.

As long as your shared library exports the napi_register_module_v1 function and uses the correct C calling convention, Node.js will load it. This makes Native AOT a perfect fit.

Native AOT Compilation

.NET Native AOT compiles your C# code directly to native machine code, producing:

  • Windows: .dll shared library
  • Linux: .so shared library
  • macOS: .dylib shared library

Node.js treats these as native addons (rename to .node extension).


Step-by-Step Implementation

1. Create the Project

Create a new console app with these properties:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <PublishAot>true</PublishAot>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
</Project>

Enter fullscreen mode Exit fullscreen mode

  • PublishAot enables Native AOT compilation
  • AllowUnsafeBlocks needed for pointer interop with N-API

2. Define the Module Entry Point

Node.js expects your shared library to export napi_register_module_v1. We use UnmanagedCallersOnly:

public static unsafe partial class RegistryAddon
{
    [UnmanagedCallersOnly(
        EntryPoint = "napi_register_module_v1",
        CallConvs = [typeof(CallConvCdecl)])]
    public static nint Init(nint env, nint exports)
    {
        Initialize();

        // Register JavaScript functions
        RegisterFunction(
            env,
            exports,
            "readStringValue"u8,
            &ReadStringValue);

        return exports;
    }
}

Enter fullscreen mode Exit fullscreen mode

Key points:

  • UnmanagedCallersOnly tells the AOT compiler to export the method
  • EntryPoint specifies the function name Node.js looks for
  • CallConvs defines the calling convention (cdecl for most platforms)
  • nint is the native-sized integer equivalent to intptr_t

3. Resolve N-API Functions Dynamically

N-API functions are exported by node.exe itself. We need to resolve them at runtime:

private static void Initialize()
{
    NativeLibrary.SetDllImportResolver(
        Assembly.GetExecutingAssembly(),
        ResolveDllImport);

    static nint ResolveDllImport(
        string libraryName,
        Assembly assembly,
        DllImportSearchPath? searchPath)
    {
        if (libraryName is not "node")
            return 0;

        // Resolve from the host process (Node.js)
        return NativeLibrary.GetMainProgramHandle();
    }
}

Enter fullscreen mode Exit fullscreen mode

4. Define N-API Function Imports

Use LibraryImport (source-generated P/Invoke) for better performance:

private static partial class NativeMethods
{
    [LibraryImport("node", EntryPoint = "napi_create_string_utf8")]
    internal static partial Status CreateStringUtf8(
        nint env, ReadOnlySpan<byte> str, nuint length, out nint result);

    [LibraryImport("node", EntryPoint = "napi_create_function")]
    internal static unsafe partial Status CreateFunction(
        nint env, ReadOnlySpan<byte> utf8name, nuint length,
        delegate* unmanaged[Cdecl]<nint, nint, nint> cb,
        nint data, out nint result);

    [LibraryImport("node", EntryPoint = "napi_get_cb_info")]
    internal static unsafe partial Status GetCallbackInfo(
        nint env, nint cbinfo, ref nuint argc,
        Span<nint> argv, nint* thisArg, nint* data);
}

Enter fullscreen mode Exit fullscreen mode

Why LibraryImport?

  • Source-generated (faster than reflection-based DllImport)
  • Trimming-compatible out of the box
  • Better error messages at compile time

5. Marshal Strings Between JavaScript and C

N-API uses UTF-8 strings. Here's how to read a string argument from JavaScript:

private static unsafe string? GetStringArg(nint env, nint cbinfo, int index)
{
    nuint argc = (nuint)(index + 1);
    Span<nint> argv = stackalloc nint[index + 1];
    NativeMethods.GetCallbackInfo(env, cbinfo, ref argc, argv, null, null);

    if ((int)argc <= index)
        return null;

    // Get the UTF-8 byte length
    NativeMethods.GetValueStringUtf8(env, argv[index], null, 0, out nuint len);

    // Allocate buffer (stack for small, pool for large)
    int bufLen = (int)len + 1;
    byte[]? rented = null;
    Span<byte> buf = bufLen <= 512
        ? stackalloc byte[bufLen]
        : (rented = ArrayPool<byte>.Shared.Rent(bufLen));

    try
    {
        fixed (byte* pBuf = buf)
            NativeMethods.GetValueStringUtf8(env, argv[index], pBuf, len + 1, out _);

        return Encoding.UTF8.GetString(buf[..(int)len)]);
    }
    finally
    {
        if (rented is not null)
            ArrayPool<byte>.Shared.Return(rented);
    }
}

Enter fullscreen mode Exit fullscreen mode

Performance optimizations:

  • stackalloc for small strings (< 512 bytes) - zero heap allocation
  • ArrayPool for larger strings - reusable buffers
  • Span<T> for memory-safe operations
  • No unnecessary string conversions

6. Implement Your Exported Function

With the plumbing in place, implementing actual functionality is straightforward:

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
private static nint ReadStringValue(nint env, nint info)
{
    try
    {
        var keyPath = GetStringArg(env, info, 0);
        var valueName = GetStringArg(env, info, 1);

        if (keyPath is null || valueName is null)
        {
            ThrowError(env, "Expected two string arguments: keyPath, valueName");
            return 0;
        }

        // Your .NET logic here
        using var key = RegistryKey.OpenBaseKey(
            keyPath, RegistryHive.LocalMachine, RegistryView.Registry64);

        return key?.GetValue(valueName) is string value
            ? CreateString(env, value)
            : GetUndefined(env);
    }
    catch (Exception ex)
    {
        // CRITICAL: Always handle exceptions to avoid crashing Node.js
        ThrowError(env, $"Registry read failed: {ex.Message}");
        return 0;
    }
}

Enter fullscreen mode Exit fullscreen mode

Important: Exception handling is critical! Unhandled exceptions in UnmanagedCallersOnly methods will crash the Node.js process.

7. Call from TypeScript

Build your project and rename the output:

dotnet publish -c Release -r win-x64
# Result: RegistryAddon.dll
# Rename to: RegistryAddon.node

Enter fullscreen mode Exit fullscreen mode

Then use it in TypeScript:

// Define the interface
interface RegistryAddon {
    readStringValue(keyPath: string, valueName: string): string | undefined;
}

// Load the native module
const registry = require('./native/win32-x64/RegistryAddon.node') as RegistryAddon;

// Call your C# function!
const sdkPath = registry.readStringValue(
    'SOFTWARE\\dotnet\\Setup\\InstalledVersions\\x64\\sdk',
    'InstallLocation');

console.log('SDK Path:', sdkPath);

Enter fullscreen mode Exit fullscreen mode


Performance Comparison

According to Microsoft's C# Dev Kit team, the .NET Native AOT approach:

Metric C++ Addon .NET Native AOT Difference
Memory Lower Slightly higher Negligible in long-running processes
Startup Instant Fast (AOT compiled) Minimal
Performance Baseline Comparable No meaningful difference
Binary Size Smaller Larger Tradeoff for tool simplicity

Key insight: For typical addon workloads (string marshalling, registry access), performance is essentially identical. The GC overhead is negligible in long-running processes like VS Code extensions.


Real-World Benefits

Simplified Development

Before (C++ with node-gyp):

Requirements: C++, Python 2.x, node-gyp, platform-specific build tools

Enter fullscreen mode Exit fullscreen mode

After (C# with Native AOT):

Requirements: .NET SDK, Node.js

Enter fullscreen mode Exit fullscreen mode

Cross-Platform Support

The same C# code works on Windows, Linux, and macOS. Build once, deploy everywhere:

# Windows
dotnet publish -r win-x64

# Linux
dotnet publish -r linux-x64

# macOS
dotnet publish -r osx-x64

Enter fullscreen mode Exit fullscreen mode

Modern Language Features

Get access to the full .NET ecosystem:

  • Async/await for I/O operations
  • LINQ for data processing
  • Records and pattern matching
  • Strong typing and IntelliSense
  • Comprehensive error handling

Common Pitfalls

1. Exception Handling

Problem: Unhandled exceptions crash Node.js
Solution: Always wrap logic in try-catch, forward errors to JavaScript

2. String Encoding

Problem: Encoding issues, buffer overruns
Solution: Use UTF-8 consistently, proper buffer sizing

3. Function Pointers

Problem: C# delegates don't work with N-API callbacks
Solution: Use delegate* unmanaged[Cdecl]<...> syntax

4. Threading

Problem: N-API functions must be called from Node.js main thread
Solution: Keep addon single-threaded, use async patterns if needed

5. Memory Leaks

Problem: Forgetting to return ArrayPool buffers
Solution: Use try-finally blocks


When to Use This Approach

✅ Great For:

  • Cross-platform Node.js tools
  • Performance-critical operations
  • Teams with .NET expertise
  • Replacing Python dependencies
  • Consolidating toolchains

❌ Not Ideal For:

  • Very simple addons (use JavaScript instead)
  • Addons requiring extensive Node.js API surface
  • Projects where C++ expertise is readily available
  • Extremely memory-constrained environments

Getting Started

Prerequisites

  • .NET 10 SDK (or .NET 11 Preview)
  • Node.js 18+ (LTS version)
  • Basic C# and Node.js knowledge

Project Template

# Create new console app
dotnet new console -n MyNodeAddon

# Edit .csproj to add:
# <PublishAot>true</PublishAot>
# <AllowUnsafeBlocks>true</AllowUnsafeBlocks>

Enter fullscreen mode Exit fullscreen mode

Publishing

# Build for target platform
dotnet publish -c Release -r win-x64

# Rename output for Node.js
mv bin/Release/net10.0/win-x64/publish/MyNodeAddon.dll \
   bin/Release/net10.0/win-x64/publish/MyNodeAddon.node

Enter fullscreen mode Exit fullscreen mode


Conclusion

.NET Native AOT opens an exciting new frontier for Node.js addon development. By leveraging N-API's language-agnostic design, you can write native addons in C# while enjoying:

  • ✅ Simpler toolchain (no Python dependency)
  • ✅ Modern language features
  • ✅ Cross-platform compatibility
  • ✅ Comparable performance to C++

The Microsoft C# Dev Kit team has proven this approach works in production. Whether you're building developer tools, performance-critical operations, or just want to unify your tech stack, .NET Native AOT for Node.js addons is worth serious consideration.

Resources


This post is based on the official Microsoft announcement from April 15, 2026, written by Drew Noakes, Principal Software Engineer at Microsoft.

Follow me on LinkedIn for more .NET and JavaScript content!