Chapter 18
In This Chapter
rundllproci:, u:, s:, a:, p:, b:, output buffers, ordinals)--ret: (int, hex, bool, hresult, wstr, astr, ptr, void)winapi convenience wrapper for common functionsdllimport, inspecting with dlllistrclrundllproc vs. when to write a pluginThis is the chapter that earns cshw the right to be called a Windows shell — not a Unix tribute act running on Windows, not a thin wrapper over cmd.exe, but a shell that understands and uses the platform it lives on.
Here's a small philosophical point that's been quietly shaping cshw all along: Windows is the largest, richest, most-documented API surface in the history of computing. The platform exposes thousands of functions across hundreds of DLLs — for graphics, audio, networking, security, system info, storage, devices, accessibility, IPC, you name it. Every major Microsoft product (and most third-party ones) ships SDKs to talk to these APIs. And almost none of that surface is reachable from a traditional Windows shell.
cshw fixes this two different ways. The first is rundllproc, which lets scripts call any Win32 function dynamically — no compilation, no wrapper code, just shell. The second is the plugin API, which lets you write a real C/C++ DLL that adds commands to cshw the same way the built-ins are added. Together they cover the whole spectrum: from "I just want to call this one API from a script" to "I want to ship a polished plugin that does ten things, with proper help text and clean integration."
This is the longest chapter of Part IV. Take it slowly — it covers more ground than any single feature in the book so far.
Before we go further, an honest framing of what this chapter unlocks.
cshw is a developer / power-user / admin shell. The features in this chapter — rundllproc and plugin DLLs — are deliberately not sandboxed. The same is true of running an .exe from cmd.exe or pasting a Python script into your interpreter: you are extending the shell process with code that has your full user privileges. So the trust model is straightforward:
cshw.exe itself can do — read your files, write to the registry, open network sockets, talk to other processes. Treat loading a plugin (rcl some.dll) with the same caution you'd treat double-clicking an .exe. Don't load plugins from untrusted sources; verify with a checksum or signature when you can.rundllproc calls real Windows APIs. That gives you the reach of the whole Win32 surface (good) and the ability to corrupt your process if you call something wrong (bad — but limited to the shell session; cshw wraps calls in __try/__except and surfaces access violations rather than dying silently). It is not a way for someone else to compromise your machine; it's a way for you to do powerful things, including powerfully wrong things, on purpose..cshw script that you source or run can do everything you can do at the prompt — exactly like a .bat/.ps1/.sh script. Read scripts before running them. Same rule as every other shell.corunproc runs in your process under your control; a genai call hits the network only when you invoke it; MessageBox only pops up when your script calls it. cshw doesn't auto-launch anything you didn't ask for.In short: cshw inherits the standard "you wrote it, you ran it, you trust it" model of a developer shell. There is no hidden privilege escalation, no automatic plugin discovery from the internet, no driver-level code. What you load is what runs. The price of rundllproc's power is the same price every shell pays for letting you call format C: — it works because it's a tool, not a toy.
With that out of the way:
A quick orientation:
| Method | When to use it | Compilation required? |
|---|---|---|
rundllproc / winapi |
Calling an existing Windows API or a DLL function once or in a loop | No — pure shell |
Plugin DLL (rcl) |
Adding a new command with its own argument parsing, help text, persistent state | Yes — C/C++ |
For one-off Win32 calls (probing the registry, calling MessageBox, getting system metrics, reading shell folders), rundllproc is the right tool. For building a real command (with proper switches, help, multi-call state, performance), write a plugin.
We'll cover them in that order — rundllproc first, since it's the easier path and you can start using it immediately.
rundllproc kernel32.dll GetTickCount
That's a working call to a real Windows API. GetTickCount is a zero-argument function in kernel32.dll that returns the number of milliseconds since boot. cshw loads kernel32.dll (or finds it already loaded — it always is), resolves GetTickCount by name, calls it with zero arguments, prints the return value, and stores it in $result.
No C++ involved. No header. No LoadLibrary boilerplate. One line of shell, one Windows API call.
rundllproc user32.dll MessageBoxW 0 "Hello from cshw!" "Greeting" 0
That pops up a Windows message box. Four arguments:
0 — the parent window handle (no parent, just show it on the desktop)"Hello from cshw!" — the message text"Greeting" — the title bar text0 — flags (0 = default, just an OK button)cshw auto-detects the types: integers become integer arguments, strings (in quotes) become wide-string pointers. Both forms work for MessageBoxW, which expects HWND, LPCWSTR, LPCWSTR, UINT.
TRY IT
Run that command. A real Windows dialog will appear, with your message and title. Close it; you'll see the dialog's exit code in your shell. That's the Win32 API calling out to your desktop, dispatched by your shell.
rundllproc auto-detects most arguments — numbers look like numbers, strings look like strings. For the cases where you need to force a type (e.g., a number you want sent as a pointer, or a string you need sent as ANSI rather than wide), use type prefixes:
| Prefix | Meaning |
|---|---|
i:N |
Signed integer (decimal or 0xHEX) |
u:N |
Unsigned integer (DWORD-size) |
p:HEX |
Raw pointer-sized value |
b:0|1 |
Boolean (also true/false/TRUE/FALSE) |
s:STRING |
Wide string (LPCWSTR) |
a:STRING |
ANSI string (LPCSTR), converted on the fly |
null |
Explicit NULL pointer |
obufw:N |
Allocate an N-wide-char output buffer, print result |
obufa:N |
Allocate an N-byte ANSI output buffer |
obuf:N |
Allocate a raw N-byte buffer, hex-dump it after |
obufd:N |
Allocate an in/out DWORD initialized to N |
obufq:N |
Allocate an in/out QWORD initialized to N |
The output-buffer types (obuf*:N) are how you call functions that return data through a pointer argument. This is everywhere in the Win32 API — GetComputerName, GetCurrentDirectory, GetEnvironmentVariable, anything that fills in a caller-provided buffer.
rundllproc --ret:bool kernel32.dll GetComputerNameW obufw:64 obufd:64
Reading this argument by argument:
--ret:bool — format the return value as TRUE/FALSE (the function returns a BOOL)kernel32.dll — the DLLGetComputerNameW — the function (wide-string variant)obufw:64 — allocate a 64-wide-char output buffer; print what the function writesobufd:64 — allocate an in/out DWORD initialized to 64; it tells the function the buffer size, and the function updates it with the actual countRun that, and cshw will:
GetComputerNameW with their addressesYou'll see your computer's hostname printed, along with the final size in the DWORD slot. That's a non-trivial Win32 API call you'd otherwise need to write C++ for, executed entirely from the shell prompt.
By default, rundllproc prints the return value as a decimal integer (plus hex). The --ret:TYPE flag changes this:
rundllproc --ret:int kernel32.dll GetTickCount # default: decimal + hex
rundllproc --ret:hex kernel32.dll GetTickCount # just hex
rundllproc --ret:bool user32.dll IsWindow p:0x10010 # TRUE / FALSE
rundllproc --ret:hresult ole32.dll CoInitialize null # HRESULT + message text
rundllproc --ret:wstr kernel32.dll GetCommandLineW # treat as LPCWSTR
rundllproc --ret:astr kernel32.dll GetEnvironmentStringsA # LPCSTR
rundllproc --ret:ptr user32.dll GetForegroundWindow # print as 0x...
rundllproc --ret:void user32.dll Sleep 100 # suppress output
The big one is --ret:wstr — many Win32 functions return a pointer to a string, and this flag tells rundllproc to dereference and print it. GetCommandLineW is a great quick win: it returns the full original command line that started your cshw process.
winapi — the convenience wrapperThere's a friendlier layer on top of rundllproc for functions you don't want to look up the DLL for:
winapi GetTickCount # = rundllproc kernel32.dll GetTickCount
winapi Sleep 250 # = rundllproc kernel32.dll Sleep 250
winapi MessageBox 0 "Hello" "cshw" 0 # = rundllproc user32.dll MessageBoxW ...
winapi MessageBoxA 0 "Hello" "cshw" 0 # forces the ANSI variant
winapi looks the function up in a built-in table of common Win32 APIs, resolves which DLL hosts it (kernel32.dll, user32.dll, gdi32.dll, advapi32.dll, shell32.dll, ole32.dll, etc.), picks the W or A variant intelligently, and dispatches the underlying rundllproc call. Most everyday uses fit the table; reach for rundllproc directly for unusual cases or private DLLs.
A useful debug switch: winapi -d FUNCTION prints which DLL/function would be called without actually calling anything.
winapi -d CreateWindow # prints "user32.dll::CreateWindowW"
winapi -d GetSystemMetrics # prints "user32.dll::GetSystemMetrics"
TIP
User-extend the resolution table by editing %APPDATA%\cshw\winapi.tsv. Each line: FunctionName<TAB>your.dll<TAB>None|W|A. Useful for remapping a function name to a different DLL, or adding functions from DLLs cshw doesn't know about.
dllimport and dlllistFor a DLL you'll call repeatedly, dllimport preloads it once and assigns an alias. Subsequent rundllproc calls can use the alias instead of the path:
dllimport user32.dll # preload, alias = "user32"
dllimport C:\MyApp\helper.dll mhelp # custom alias "mhelp"
rundllproc user32 GetForegroundWindow # using the alias
rundllproc mhelp DoSomething # custom DLL by alias
dlllist # see what's currently loaded
dllunload mhelp # unload one
This is mainly a performance and tidiness convenience — you avoid the repeated LoadLibrary cost and you write shorter command lines. Inside a tight loop calling the same function many times, preloading is the right move.
rundllproc is real, low-level, dangerous Windows API access. Two things to keep in mind:
SEH protection. rundllproc invokes target functions under __try/__except. Access violations and most hardware exceptions are caught and reported instead of crashing the shell. Most. Corrupting the process heap or stack with a bad call can still leave the shell unhappy. Don't expect bulletproof recovery from arbitrarily wrong calls — expect "the shell prints an exception code instead of crashing."
Calling conventions and signature mismatches. On x64 there's effectively one calling convention; arguments are passed in registers up to 4, then on the stack. rundllproc correctly passes up to 16 DWORD_PTR-sized arguments. The function still has to want the shape you're giving it — calling MessageBoxW with two ints when it expects four pointers is undefined behavior. Look up the real signature before calling.
WARNING
Functions returning 32-bit signed integers (like lstrcmpW returning -1) will print as large unsigned values on x64, because the upper 32 bits of the return register are zero. Use --ret:hex if that's clearer, or compare against 0xFFFFFFFF. The integer return formatting was a design tradeoff: DWORD_PTR is the right type for most modern Win32 returns, but it's not always right for legacy ones.
rundllproc plus the Windows Registry API in pure shell. We'll read the current Windows product name:
# Open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
rundllproc --ret:hresult advapi32.dll RegOpenKeyExW \
p:0x80000002 \
s:"SOFTWARE\Microsoft\Windows NT\CurrentVersion" \
i:0 \
u:0x20019 \
obufq:0
# The handle is in the obufq slot; in practice, capture it into a variable
# via $result and reuse for RegQueryValueExW.
You can wire that up into a procedure that returns the value as $result. The point isn't that you'd actually want to write registry-reading code this way (cshw also has a built-in reg command); it's that you could, and the same approach reads any Win32 API on the system.
REMEMBER
rundllproc is the Windows-shell answer to Python's ctypes or PowerShell's Add-Type / P/Invoke. The advantage over those: no language switch, no compilation, no ceremony. Just a shell command. The cost: less type safety; you're responsible for matching the function's real signature. Use it when the alternative is "write a separate Python script just to call this one API," and you'll save real time.
rundllproc is the easy path. The plugin API is the real path — for when you want to write a polished new command in C/C++ and have it integrate as cleanly as any built-in.
A cshw plugin is a Windows DLL that exports exactly one required function:
RegisterCommandLibrary — returns information about the plugin's commands. Called when the DLL is loaded via rcl. Without it, rcl refuses the DLL outright: "does not export RegisterCommandLibrary".Three exports are optional:
UnregisterCommandLibrary — called when the DLL is unloaded via urcl, for cleanup. Strongly recommended if your plugin owns anything that needs releasing, but the host checks for it and simply skips the call when it is absent. A DLL exporting only RegisterCommandLibrary loads, runs its commands, and unloads cleanly.SetShellAccessFuncs (v2) — receives the shell-access table, covered below.InitializeLibrary (v2) — receives any extra args you passed to rcl.With that one required export your plugin's commands already become first-class members of the shell — same argument parsing, same redirection support, same help system, same shadowing of intrinsics.
cshw ships a single SDK header, CShellPluginAPI.h. Include it; you get the structures and macros you need to define a plugin without ceremony:
#include "CShellPluginAPI.h"
(You will see #define CSHW_PLUGIN_EXPORTS before that include in older examples. It is harmless, but it does nothing — no part of the header tests that macro.)
The header declares:
CShwPluginCommandDef — definition of a single command (name, description, init/do/help functions)CShwPluginLibraryInfo — top-level metadata about the plugin (name, version, command array, optional cleanup)init, do, help, and cleanup callbacksCShwShellAccessFuncs table — function pointers for plugins that need to call back into the shell (read variables, write to stdout, execute another command)CSHW_EXPORT_REGISTER and CSHW_EXPORT_UNREGISTER — that emit the boilerplate exports for youHere is a complete, working plugin in one .cpp file. It adds a single new command, wordstats, that reports word/line/character counts from a file or piped input:
// wordstats_plugin.cpp -- a complete cshw plugin in one file
#define CSHW_PLUGIN_EXPORTS
#include "CShellPluginAPI.h"
#include <string>
#include <cwctype>
// --- The command's "do" function -----------------------------------------
static BOOL DoWordStats(CSHW_SHELL_HANDLE pShell,
int argc,
const wchar_t** argv,
CShwPluginParamInfo* info)
{
// Determine input source
FILE* fIn = info->fInput;
FILE* fLocal = NULL;
if (argc >= 2 && argv[1][0] != L'-' && argv[1][0] != L'/')
{
// A file was named; open it
if (_wfopen_s(&fLocal, argv[1], L"r") != 0 || !fLocal)
{
fwprintf(info->fOutput, L"wordstats: cannot open %ws\n", argv[1]);
info->errorCode = CSHW_PLUGIN_NOT_FOUND;
return FALSE;
}
fIn = fLocal;
}
// Accumulate
unsigned long long lines = 0, words = 0, chars = 0;
int prevWs = 1; // start "in whitespace"
wint_t ch;
while ((ch = fgetwc(fIn)) != WEOF)
{
chars++;
if (ch == L'\n') lines++;
if (iswspace(ch))
{
prevWs = 1;
}
else
{
if (prevWs) words++;
prevWs = 0;
}
}
fwprintf(info->fOutput, L"Lines: %llu\n", lines);
fwprintf(info->fOutput, L"Words: %llu\n", words);
fwprintf(info->fOutput, L"Characters: %llu\n", chars);
if (fLocal) fclose(fLocal);
info->errorCode = CSHW_PLUGIN_SUCCESS;
return TRUE;
}
// --- The command's "help" function ---------------------------------------
static BOOL HelpWordStats(CShwPluginParamInfo* info)
{
fwprintf(info->fOutput,
L"Usage: wordstats [FILE]\n\n"
L"Report line, word, and character counts. If FILE is omitted,\n"
L"reads from standard input (so it composes with pipelines).\n"
L"\nExamples:\n"
L" wordstats report.txt\n"
L" type *.log | wordstats\n");
return TRUE;
}
// --- The command table ---------------------------------------------------
static CShwPluginCommandDef s_commands[] = {
{
L"wordstats", // name
L"Count lines, words, and chars", // description
NULL, // no .man file
NULL, // no custom init
DoWordStats, // execute
HelpWordStats, // help
TRUE, // enabled
NULL // reserved
}
};
// --- The library info ----------------------------------------------------
static CShwPluginLibraryInfo s_libInfo = {
CSHW_PLUGIN_API_VERSION, // apiVersion
L"WordStats", // libraryName
L"1.0.0", // libraryVersion
L"Text statistics command", // libraryDescription
L"ws", // suggested prefix
sizeof(s_commands) / sizeof(s_commands[0]),
s_commands,
NULL, // no cleanup callback
0, NULL, // v2: no window classes
{ NULL, NULL } // reserved
};
// --- The required DLL exports --------------------------------------------
CSHW_EXPORT_REGISTER(s_libInfo)
CSHW_EXPORT_UNREGISTER(/* nothing to clean up */)
Build that as a DLL. Visual Studio's "Dynamic-Link Library" project template is the easiest path; you can also build from the command line:
cl /LD /EHsc /std:c++17 wordstats_plugin.cpp /I path\to\cshw\sdk /Fe:wordstats.dll
Now load it:
rcl wordstats.dll
Output:
Loaded command library: wordstats.dll
Name: WordStats
Version: 1.0.0
Prefix: ws
Commands: 1
And use it:
wordstats README.md
# Lines: 127
# Words: 1843
# Characters: 12057
type *.cpp | wordstats
# (counts across all C++ files in the directory)
ws:wordstats README.md # explicit prefix form
That's a fully integrated cshw command in about 90 lines of C++. The prefix-form (ws:wordstats) is always available; the unprefixed form is too unless rcl /prefixonly was used.
The example above used four cshw-specific types. Quick reference:
CShwPluginCommandDef — one entry per command. Fields: name, description, manFilePath (path to a .man file or NULL), initFunc, doFunc, helpFunc, enabled flag, reserved. The do and help functions are required; init is optional (it runs once at load time per command, useful if you need to do per-command setup).CShwPluginLibraryInfo — the top-level metadata. Returned to cshw from RegisterCommandLibrary. Fields: API version (must equal CSHW_PLUGIN_API_VERSION), library name, version, description, suggested prefix, command-table size and pointer, optional cleanup function, optional window-class count and pointer (for plugin commands that create Win32 windows — covered briefly below), and reserved fields.CShwPluginParamInfo — passed to your do and help functions on every call. Carries the I/O streams (fInput/fOutput — but see the CRT warning below before using them for output), the command name, the raw argument line, an error-code field for you to set on failure, a result-text buffer, and access to the parsed switch map.CSHW_SHELL_HANDLE — opaque pointer to the shell instance. Pass this to the shell-access functions when you need to call back into cshw.Write through
WriteOutput, notfOutput, and never tostdout.This is the one rule worth internalising, and it is not the rule earlier printings of this chapter gave. They told you to use
fwprintf(info->fOutput, ...). That produces the wrong bytes.
fOutputis aFILE*owned by cshw's C runtime. cshw.exe links the static CRT, so your DLL — whether you build it/MTor/MD— always has a separate CRT, with its own stream table, orientation and translation state. Writing to another CRT'sFILE*is unsupported, and the damage is silent. Writing the same text under the same>redirect:
route bytes on disk intrinsic echoplugin_fout(narrow text)WriteOutput()plugin_fout(narrow text)fwprintf(fOutput, …)p\0l\0u\0g\0…(raw UTF-16)So a plugin that follows the obvious path writes a file no other tool can read, while every other producer in the shell writes text. Mixing a narrow
fprintfand a widefwprintfonfOutputin one command produced no output at all. Building the plugin/MDdoes not help — it is still not the host's CRT.There are two correct routes. Both emit bytes identical to an intrinsic and both honour
>,>>,|and backtick capture.1.
WriteOutput/WriteErrorfrom the shell-access table. They run inside cshw's CRT. Simplest when you just have text:g_access->WriteOutput(pShell, L"some text\n");2.
CshwOpenOutputStream(info)when you wantfwprintfback. The param block carries the raw OS handles behind the streams (hOutput,hInput), and this helper duplicates one into aFILE*owned by your CRT:FILE* out = CshwOpenOutputStream(info); if (out) { fwprintf(out, L"%ls\n", text); CshwCloseStream(out); // close before returning }The helper is
static __inlinein the SDK header, so it compiles into your DLL and every CRT call inside it is yours. The handle is duplicated, so closing your stream never disturbs cshw's; duplicated handles share one file object, so your writes land where the host left off rather than overwriting.This is deliberately not solved by requiring plugins to link the same runtime as the host. A Win32
HANDLEis an operating-system object, so passing it instead of aFILE*keeps the ABI runtime-agnostic — a plugin built with a different MSVC, or a different compiler entirely, still works.The examples further up this chapter still use
fwprintf(info->fOutput, …). They work well enough to read on a console, which is why this went unnoticed; convert them toWriteOutputbefore shipping anything whose output gets redirected to a file.It matters doubly under concurrency. Coroutines (
corunproc) and concurrent pipeline stages execute commands on worker threads, and cshw deliberately does not redirect the process-wide file descriptor 1 on those threads — it can't, because descriptors 0/1/2 are process-global, so redirecting one on a worker would hijack the main thread's console mid-print. A plugin that writes tostdoutdirectly will therefore leak past its own redirect the moment someone runs it from a coroutine or a pipeline stage. Write tofOutputand the problem never exists.The same applies to input: read
fInput, notstdin.
A plugin that wants to use shell features (read a variable, run another command, write to stderr) does so through the shell-access function table. To get the table, export SetShellAccessFuncs:
#include "CShellPluginAPI.h"
static CShwShellAccessFuncs* g_pShell = NULL;
extern "C" __declspec(dllexport)
void SetShellAccessFuncs(CShwShellAccessFuncs* p)
{
g_pShell = p; // stash for later use
}
cshw calls this right after RegisterCommandLibrary, before any of your commands execute. From your do functions, you can then do things like:
// Read a shell variable
const wchar_t* userName = g_pShell->GetVariable(shellHandle, L"USERNAME");
// Set a variable for later script code to read
g_pShell->SetVariable(shellHandle, L"mystatus", L"complete");
// Write to the shell's output (respecting redirection)
g_pShell->WriteOutput(shellHandle, L"Processing complete.\n");
// Execute another cshw command
int rc = g_pShell->ExecuteCommand(shellHandle, L"echo Hello from plugin");
Here is the whole table. Twelve entries, and none of them is hard:
| Function | What it does |
|---|---|
GetVariable(shell, name) |
Read a shell variable. Returns "" if unset. See the lifetime note below. |
SetVariable(shell, name, value) |
Set a shell variable the script can read afterwards |
SetVariableInt(shell, name, n) |
Same, for an integer |
DeleteVariable(shell, name) |
Remove a variable |
WriteOutput(shell, text) |
Write to the command's output, honouring redirection |
WriteError(shell, text) |
Write to stderr |
ExecuteCommand(shell, cmdline) |
Run a cshw command line. Returns the command's exit status |
GetCurrentDirectory(shell) |
The working directory. See the lifetime note below. |
SetCurrentDirectory(shell, path) |
Change it — updates $cwd, $owd and the dir stack, exactly as cd does |
HasSwitch(switchMapPtr, name) |
Was this switch passed? |
GetSwitchValue(switchMapPtr, name) |
Its value, for /name:value forms |
DispatchScriptEvent(shell, hwnd, msg, wParam, lParam) |
Surface a raw Win32 message to script bindevent handlers (v2; NULL on older hosts) |
ExecuteCommand runs in your caller's shell, not a copy — variables it sets, directories it changes, and jobs it starts are all still there when it returns. Its return value is the command's $status, so you can tell whether what you ran actually worked.
⚠️ Pointer lifetime.
GetVariableandGetCurrentDirectoryreturn a pointer into a thread-local buffer that the next call to the same function on that thread overwrites. Copy the string if you need to keep it. This is the one place in the API where holding a pointer a moment too long silently gives you the wrong value:const wchar_t* a = g_pShell->GetVariable(h, L"first"); std::wstring keep = a; // right const wchar_t* b = g_pShell->GetVariable(h, L"second"); // `a` now reads "second" too -- same buffer.
Your command is handed the same three views of its own invocation that a built-in gets, and you are free to use whichever suits the command you are writing — or all three at once:
| View | What it is | Reach it via |
|---|---|---|
argv / argc |
the operands, already tokenised and unquoted | parameters to your do function |
| the switch map | the parsed flags | HasSwitch / GetSwitchValue with info->switchMapPtr |
| the raw line | exactly what the user typed | info->argLine |
This is not an accident of the plugin layer — it is the shell's own convention. cshw's built-ins read vecTokens (the same list your argv is built from) in fourteen source files, consult the switch map in over two hundred places, and fall back to the raw line in a few dozen where a command needs something the cooked forms cannot express. A plugin command is a first-class citizen here, not a second-class one: same three views, same freedom to pick.
The one thing to internalise is how the first two divide the work. By the time your do function runs, cshw has already lifted every recognised switch out of argv and into the switch map. Given:
mycmd /verbose report.txt
your argv is { "mycmd", "report.txt" } — argc is 2, and /verbose is nowhere in it. It has been parsed into the switch map, and the only way to read it is through the table:
if (g_pShell->HasSwitch(info->switchMapPtr, L"verbose"))
g_pShell->WriteOutput(shell, L"verbose mode\n");
const wchar_t* out = g_pShell->GetSwitchValue(info->switchMapPtr, L"out");
Note the name has no leading / or -, and the map preserves case, so /V and /v are different switches.
Use it when the cooked views cannot express what you need — an argument that must keep its quoting, a mini-language of your own, a flag spelling cshw does not recognise. info->argLine is the argument line exactly as typed, and info->cmdName is the command name. Measured, for the command tp_args …:
| you type | argv |
argLine |
|---|---|---|
cmd one two |
{cmd, one, two} |
one two |
cmd /verbose one |
{cmd, one} |
/verbose one |
cmd "a b" c |
{cmd, a b, c} |
"a b" c |
cmd one > out.txt |
{cmd, one} |
one > 'out.txt' |
So argLine holds the command's arguments but not its name, it keeps switches that argv has lost, and it keeps the quotes that argv has had removed. All of which is what "raw" should mean.
⚠️
argLinealso contains the redirection. Look at the last row:> 'out.txt'is still in there. Redirection belongs to the shell, not to your command, and it has already been acted on before you are called — but nobody removed it from the raw line.If you parse
argLine, stop at the first>,>>,<,2>or|, or you will treat the shell's plumbing as your own arguments. This is not hypothetical: cshw's ownrclcommand had exactly this bug. It readargLinelooking for a namespace prefix, accepted any token that did not begin with-or/, and sorcl plugin.dll > /dev/nullregistered every command under the prefix>. Redirecting a command's output must never change what the command does.
Return TRUE from your do function on success, FALSE on failure, and set info->errorCode before you return. cshw maps it onto the shell's own error vocabulary and publishes $status, so a script can branch on your command the same way it branches on a built-in:
errorCode |
Meaning |
|---|---|
CSHW_PLUGIN_SUCCESS |
Worked |
CSHW_PLUGIN_FAILURE |
General failure |
CSHW_PLUGIN_INVALID_ARG |
Bad arguments |
CSHW_PLUGIN_NOT_FOUND |
Something the command needed was missing |
CSHW_PLUGIN_SYNTAX_ERROR |
Malformed input |
CSHW_PLUGIN_WIN_ERROR |
A Win32 call failed — also set info->winError |
mycmd something
if ($status != 0) then
echo "the plugin command failed"
endif
TECHNICAL STUFF
The plugin API is at version 2. Version 1 plugins didn't have SetShellAccessFuncs or window-class support; v2 adds both, plus an optional InitializeLibrary export that receives any extra arguments the user passed to rcl. The conventional form uses -- to separate plugin args from cshw's own:
rcl my.dll myprefix -- --config:foo.json --verbose
rcl my.dll -- --port:8080 # no prefix, args follow
The -- is optional when the trailing tokens don't look like a prefix anyway, but writing it out makes scripts readable. The apiVersion field in CShwPluginLibraryInfo is checked at load — version mismatches fail cleanly with a message rather than crashing. Set it to CSHW_PLUGIN_API_VERSION always; bump it when the SDK header bumps.
If your plugin shows a window (a status display, a progress bar, a custom dialog), v2 of the API lets you register window classes through cshw rather than fighting the threading model:
// One class definition per window class your plugin creates
static CShwPluginWindowClassDef s_classes[] = {
{
L"MyPlugin.Counter", // class name (unique process-wide)
CS_HREDRAW | CS_VREDRAW, // style
0, // cbWndExtra
NULL, // background brush (NULL = default)
NULL, // cursor (NULL = arrow)
NULL, // icon
MyWndProc, // your window procedure
{ NULL, NULL, NULL, NULL }
}
};
Then include them in the library info via the windowClassCount and windowClasses fields (use the CSHW_DEFINE_LIBRARY_WITH_WNDCLASSES macro if you don't want to write the brace-initializer yourself). cshw registers the classes for you, subclasses them so script-bound events (WM_COMMAND, etc.) surface to scripts, and unregisters them when the plugin unloads. Your WNDPROC is a normal Win32 procedure — no cshw-specific calls inside it.
This is in the API for the kinds of plugins that genuinely earn their UI — a custom dashboard, a real-time monitor, a control panel for a hardware integration. Most plugins won't need it.
A short tour of the commands for inspecting and unloading plugins:
cmdliblistShows what plugin DLLs are currently loaded:
cmdliblist # summary
cmdliblist /v # also list every command each library contributes
Output:
Loaded command libraries:
WordStats
Version: 1.0.0
Prefix: ws
Path: C:\Plugins\wordstats.dll
Commands: 1
Stats
Version: 2.1.3
Prefix: stats
Path: C:\Plugins\stats.dll
Commands: 3
(library is a separate command — it loads .cshw script libraries, not plugin DLLs. They're easy to mix up by name; reach for cmdliblist/rcl/urcl for DLLs.)
urcl PATH or urcl LIBRARY_NAMEUnload a plugin:
urcl wordstats.dll # by path
urcl WordStats # by library name
cshw calls the plugin's UnregisterCommandLibrary callback (your cleanup hook), unregisters the commands, unregisters any window classes, and FreeLibrarys the DLL. Any commands the plugin shadowed are restored to their originals.
You probably don't want to type rcl every time you start the shell. cshw checks three places at startup for plugins to preload:
cshw.ini file in the same directory as cshw.exe: [CommandLibraries]
C:\Plugins\mylib.dll=mylib
C:\Plugins\tools.dll=tools:prefixonly
HKEY_CURRENT_USER\Software\cshw\CommandLibraries. Value names are DLL paths; value data is the prefix.CSHW_CMDLIBS environment variable, semicolon-separated: CSHW_CMDLIBS=C:\lib1.dll;C:\lib2.dll:prefix2
Pick whichever fits your distribution model. Per-user customization usually lives in the registry; system-wide plugins shipped with an application typically use the INI; on-the-fly debugging often uses the environment variable.
You now have three ways to add functionality to cshw — rundllproc, winapi, and plugins. A decision guide:
| Use... | When |
|---|---|
rundllproc |
One-off Win32 API calls, ad-hoc experimentation, automation involving rarely-used APIs |
winapi |
Calling common Win32 APIs without remembering which DLL hosts them |
| Plugin DLL | Building a polished command for repeated use, performance-critical inner loops, wrapping a C/C++ library, anything that needs persistent state |
A useful pattern: prototype with rundllproc to verify the Win32 calls work the way you expect, then promote the working pieces into a plugin for production. The plugin gets you proper argument parsing, real help text, faster execution (one fixed-resolution call instead of per-invocation GetProcAddress), and tidier scripts.
TIP
A well-written plugin can completely replace a multi-hundred-line shell script. The shell script orchestrates; the plugin does the heavy lifting in compiled C/C++. The combination is enormously powerful for tasks where shell-level expressiveness fits the orchestration layer but pure-shell processing would be too slow — log processing at scale, file scanning over millions of files, anything CPU-bound. Five lines of cshw script calling into a plugin can match (or beat) the throughput of a hand-written tool, while staying inspectable and modifiable at the shell level.
Most shells treat the platform as something to get around, not something to use. Bash treats Windows as alien territory; PowerShell sits on top of .NET and pretends the rest of Win32 doesn't exist; cmd.exe is a 1990s relic that doesn't even have variables that work properly. None of them lets you reach down to the platform with the directness cshw does.
rundllproc and the plugin API are the features that flip this. Anything Windows can do, your shell can do — because they're the same thing, dispatched through the same loader, talking to the same exported entry points. The Win32 API is the world's most thoroughly documented programming surface; cshw makes it part of the shell's vocabulary. A few hundred thousand functions, all reachable from a prompt.
This is what a Windows shell should have been. Forty years late, but here we are.
That's platform extension — rundllproc for reaching any Win32 API from a script, and the plugin API for adding real compiled commands to the shell. You've now seen almost the full reach of cshw: scripting (Part III), parallelism (Chapters 14–15), networking (Chapter 16), AI integration (Chapter 17), and native platform extension (this chapter).
One power feature remains, and it builds directly on this one. Chapter 19 covers the tsrvd daemon family — standalone, supervised servers that run in their own process, including a ready-to-run mail stack (SMTP, POP3, IMAP), an FTP server, and a web server that speaks HTTP/1.1, HTTP/2, and HTTP/3. Those servers are themselves native plugins, built against a server-side cousin of the plugin ABI you just learned. It's the capstone of Part IV: concurrency, networking, and native code combined into services you can actually keep running.
Chapter 20 then covers printing — lp and friends, and turning documents into PDFs or images with no printer attached.
After that, Part V is the celebratory wrap-up — three Top Tens and a one-page cheat sheet:
If you've made it this far, you can do things in cshw that almost no shell user anywhere can do in their preferred shell. Concurrent network scrapers; AI-augmented log analysis; native Win32 API calls without leaving the prompt; first-class plugin extension in real C++. That's a real skill set — and you got there by working through one book.
The fun part is just beginning: writing the scripts that solve your problems, building the plugins for your team, gluing your daily tools together with the toolkit you now have. The shell isn't a thing you read about; it's a thing you live in. Welcome to your new desk.
See you in Chapter 19.