Native Functions and Hooks
This is low-level, unsafe territory. A wrong calling convention, a mismatched delegate signature, or a bad register edit in a mid-hook can crash the game server. Test on a disposable server first.
Native interop splits across three services: Core.GameData (APIIGameDataService) resolves named signatures/offsets/patches shipped with your plugin, Core.Memory (APIIMemoryService) turns raw addresses into callable, hookable functions (or raw memory to mid-hook directly), and Core.GameHooks (APIIGameHooks) wraps the common engine callbacks in typed categories.
Resolving Addresses
From Your Plugin's GameData
Each plugin ships its own resources/gamedata/*.jsonc with signatures, offsets and patches per platform, keyed by name - signatures in signatures.jsonc, offsets in offsets.jsonc and byte patches in patches.jsonc. Look them up with TryGetSignature/TryGetOffset:
if (!Core.GameData.TryGetSignature("CBaseEntity::DispatchSpawn", out nint dispatchSpawnAddress))
{
Core.Logger.LogWarning("Signature not found");
return;
}
if (!Core.GameData.TryGetOffset("CCSPlayer_ItemServices::GiveNamedItem", out nint giveNamedItemOffset))
{
return;
}The full APIIGameDataService surface:
| Member | Returns | Defined in |
|---|---|---|
HasSignature(string signatureName) | bool | signatures.jsonc |
GetSignature(string signatureName) | nint | signatures.jsonc |
TryGetSignature(string signatureName, out nint) | bool | signatures.jsonc |
HasOffset(string offsetName) | bool | offsets.jsonc |
GetOffset(string offsetName) | int | offsets.jsonc |
TryGetOffset(string offsetName, out nint) | bool | offsets.jsonc |
HasPatch(string patchName) | bool | patches.jsonc |
ApplyPatch(string patchName) | void | patches.jsonc |
RevertPatch(string patchName) | void | patches.jsonc |
GetOffset hands the offset back as an int, TryGetOffset as an nint.
From a Raw Pattern or VTable Name
Core.Memory can also scan a library directly, skipping gamedata entirely:
nint? patternAddress = Core.Memory.GetAddressBySignature(Library.Server, "55 8B EC 83 EC 08 8B 45 08 5D C3");
nint? vtableAddress = Core.Memory.GetVTableAddress(Library.Server, "CCSPlayer_ItemServices");
nint? interfaceAddress = Core.Memory.GetInterfaceByName("VEngineServer");APILibrary exposes the module names used by these lookups:
| Member | Module |
|---|---|
Library.Engine | engine2 |
Library.Tier0 | tier0 |
Library.Server | server |
Library.NetworkSystem | networksystem |
Other Memory Helpers
The same service resolves cross-references, inspects object pointers, converts raw addresses and allocates memory:
nint resolved = Core.Memory.ResolveXrefAddress(xrefAddress);
string? vtableName = Core.Memory.GetObjectPtrVtableName(entityAddress);
bool hasVTable = Core.Memory.ObjectPtrHasVtable(entityAddress);
bool isBaseEntity = Core.Memory.ObjectPtrHasBaseClass(entityAddress, "CBaseEntity");
CBaseEntity entity = Core.Memory.ToSchemaClass<CBaseEntity>(entityAddress);
IServerSideClient client = Core.Memory.ToServerSideClient(clientAddress);
nint block = Core.Memory.Alloc(64);
block = Core.Memory.Resize(block, 128);
Core.Memory.Free(block);| Member | Returns |
|---|---|
ResolveXrefAddress(nint xrefAddress) | nint, the address the xref points at |
GetObjectPtrVtableName(nint address) | string?, null when not found |
ObjectPtrHasVtable(nint address) | bool |
ObjectPtrHasBaseClass(nint address, string baseClassName) | bool |
ToSchemaClass<T>(nint address) | T, where T : class, ISchemaClass<T> |
ToServerSideClient(nint address) | APIIServerSideClient |
Alloc(ulong size) | nint, the address of the allocated block |
Resize(nint pointer, ulong newSize) | nint, the address of the resized block |
Free(nint pointer) | void |
Declaring a Delegate
Wrapping a native function needs a delegate matching its exact signature and calling convention:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate nint DispatchSpawnDelegate(nint pEntity, nint pKeyValues);Wrapping and Calling It
Wrap by address or by vtable + index; the resulting APIIUnmanagedFunction`1 exposes Address (nint) and two delegate-typed members: Call (goes through any installed hooks) and CallOriginal (skips the hook chain).
IUnmanagedFunction<DispatchSpawnDelegate> func =
Core.Memory.GetUnmanagedFunctionByAddress<DispatchSpawnDelegate>(dispatchSpawnAddress);
// or: Core.Memory.GetUnmanagedFunctionByVTable<DispatchSpawnDelegate>(vtableAddress.Value, 15);nint address = func.Address;
nint result = func.Call(pEntity, pKeyValues);
nint resultUnhooked = func.CallOriginal(pEntity, pKeyValues);Hooking It
AddHook takes a builder that receives "the next function in the chain" and must return your replacement delegate. Skipping next() skips the original call entirely. It returns the hook's Guid, which RemoveHook takes.
Guid hookId = func.AddHook(next =>
{
return (pEntity, pKeyValues) =>
{
// pre logic
nint result = next()(pEntity, pKeyValues);
// post logic
return result;
};
});
// later
func.RemoveHook(hookId);Hooks are cleaned up automatically on unload, but removing them yourself once done is still good practice.
Mid-Function Hooks
When hooking function entry/exit isn't precise enough, Core.Memory.GetUnmanagedMemoryByAddress wraps an arbitrary address in an APIIUnmanagedMemory so you can hook mid-function, with read/write access to the CPU registers at that point:
IUnmanagedMemory mem = Core.Memory.GetUnmanagedMemoryByAddress(dispatchSpawnAddress);
Guid midHookId = mem.AddHook((ref MidHookContext ctx) =>
{
Console.WriteLine($"RIP=0x{ctx.RIP:X}, RAX=0x{ctx.RAX:X}");
ctx.RAX = 0x1337; // example register edit
});
// later
mem.RemoveHook(midHookId);AddHook here takes a APIMidHookDelegate (void (ref MidHookContext)) and returns a Guid, and the wrapper exposes Address. See APIMidHookContext for the full register list - every general-purpose register (RAX, RBX, RCX, RDX, RSI, RDI, RBP, RSP, R8-R15, RIP, RFLAGS, plus the internal TRAMPOLINE_RSP) and XMM0-XMM15 as APIXmm structs (fixed buffers U8, U16, U32, U64, F32, F64). MidHookContext.ToString() dumps every register in one go.
Hook Modes and Results
APIHookMode picks when a hook runs, APIHookResult tells the framework what to do with the call afterwards:
| Value | Number | When it runs |
|---|---|---|
HookMode.Pre | 0 | Before the game processes the call. |
HookMode.Post | 1 | After the game processed the call. |
| Value | Number | Effect |
|---|---|---|
HookResult.Continue | 0 | Following hooks and the original function run. |
HookResult.Stop | 1 | Following hooks and the original function are cancelled. |
HookResult.Handled | 2 | Following hooks are cancelled, the original function still runs. |
HookResult.CancelOriginal | 3 | Following hooks run, the original function is cancelled. |
Stop and Handled have no effect in post hooks - the original function
has already run by the time they are set.
Delegate-based hooks such as Core.GameEvent and the client command/chat and net message hooks return the result from the handler. Game hooks below take it on the context with SetHookResult(HookResult) instead, and hooks whose native function returns a value expose that separately: SetReturn(...) in a Pre context, and a settable Return on the matching Post context.
Higher-Level Alternative: Game Hooks
Core.GameHooks (APIIGameHooks) wraps the vtable-hook plumbing above into typed categories with separate Pre/Post delegates - no manual delegate/signature bookkeeping. Example, hooking entity damage via APIITakeDamageEntityHook:
private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
var entity = ctx.Params.Entity;
ref var info = ref ctx.Params.Info;
// ctx.SetHookResult(HookResult.Stop); // to block the damage
}
// Register in Load():
Core.GameHooks.Entities.TakeDamage.Pre += OnTakeDamagePre;The same handler can be registered by attribute instead. APIGameHookHandler takes the mode in its constructor, sits on a method whose signature matches the hook's delegate, and allows one attribute per method (AllowMultiple = false); the methods are discovered on registered instances - see Using Attributes:
[GameHookHandler(HookMode.Pre)]
private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
// ctx.SetHookResult(HookResult.Stop); // to block the damage
}Categories
| Category | Access path | Hooks |
|---|---|---|
| Controller | Core.GameHooks.Controller | ProcessUsercmds, SimulateUserCommands |
| Entities | Core.GameHooks.Entities | TakeDamage, StartTouch, Touch, EndTouch, AcceptInput, FireOutput |
| Items | Core.GameHooks.Items | CanAcquire, GetItemInLoadout |
| Movement | Core.GameHooks.Movement | RunCommand, SetupMove, ProcessMovement, CheckFalling, CategorizePosition, TryPlayerMove, WalkMove, Friction, AirAccelerate, AirMove, OnJumpModern, OnJumpLegacy, CheckJumpButtonModern, CheckJumpButtonLegacy, LadderMove, CanUnduck, Duck, CheckVelocity, WaterMove, CheckWater, MoveInit, FullWalkMove, CheckParameters, PlayerMove, GroundAccelerate |
| Pawn | Core.GameHooks.Pawn | PostThink, CanMove |
| Weapons | Core.GameHooks.Weapons | Drop, CanUse |
| Datamaps | Core.GameHooks.Datamaps | Datamap (think/touch/use) function hooks, grouped by owning schema class |
Items.GetItemInLoadout is the one exception that needs a server setting: subscribing its Pre/Post throws unless FollowCS2ServerGuidelines is disabled in core.jsonc.
Hook Params
Every hook has a Pre and a Post context, both carrying a Params field with the arguments of the call:
| Hook | Params members |
|---|---|
Controller.ProcessUsercmds | Player (IPlayer), Usercmds (List<IUserCmd>), Paused (bool), Margin (float) |
Controller.SimulateUserCommands | Player (IPlayer) |
Entities.TakeDamage | Entity (CBaseEntity), Info (ref CTakeDamageInfo), DamageResult (CTakeDamageResult*, may be null) |
Entities.StartTouch / Touch / EndTouch | Entity and OtherEntity (both CBaseEntity) |
Entities.AcceptInput | Identity (CEntityIdentity), EntityInstance (CEntityInstance), DesignerName (string), InputName (string), Activator and Caller (both CEntityInstance?), VariantValue (ref CVariant<CVariantDefaultAllocator>), OutputId (int) |
Entities.FireOutput | EntityIO (ref CEntityIOOutput), DesignerName (string), OutputName (string), Activator and Caller (both CEntityInstance?), VariantValue (ref CVariant<CVariantDefaultAllocator>), Delay (float) |
Items.CanAcquire | Player (IPlayer), EconItemView (CEconItemView), WeaponVData (CCSWeaponBaseVData?), AcquireMethod (APIAcquireMethod) |
Items.GetItemInLoadout | Player (IPlayer), Team (Team), Slot (loadout_slot_t) |
Pawn.PostThink / CanMove | Player (IPlayer) |
Weapons.Drop | Player (IPlayer), Weapon (CBasePlayerWeapon?), SwappingWeapon (bool) |
Weapons.CanUse | Player (IPlayer), Weapon (CCSWeaponBase) |
Movement.RunCommand | Player (IPlayer), UserCmd (APIIUserCmd) |
Movement.SetupMove | Player (IPlayer), UserCmd (APIIUserCmd), MoveData (APIIMoveData) |
every other Movement hook | Player (IPlayer), MoveData (APIIMoveData) |
Some hooks carry extra settable params: Movement.AirAccelerate adds WishDirection (Vector), WishSpeed (float) and Acceleration (float), Movement.GroundAccelerate adds WishDirection, FrameTime (float, read-only), WishSpeed and Acceleration, Movement.TryPlayerMove adds FirstDest (Vector), FirstTrace (APITraceResult, read-only) and IsSurfing (bool), Movement.CategorizePosition a StayOnGround (bool), and Movement.FullWalkMove a Ground (bool).
IMoveData and IUserCmd wrap native pointers - IMoveData.From(address) and IUserCmd.From(address) build one from an address, and Address/TypedAddress are exposed back.
Return Values
Hooks whose original function returns a value expose it on the context:
| Hook | Return type | Set it in Pre | Read/overwrite it in Post |
|---|---|---|---|
Core.GameHooks.Items.CanAcquire | AcquireResult | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Items.GetItemInLoadout | CEconItemView? | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Weapons.CanUse | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Pawn.CanMove | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Movement.CanUnduck | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Movement.LadderMove | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Movement.MoveInit | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Movement.PlayerMove | bool | ctx.SetReturn(...) | ctx.Return |
Core.GameHooks.Movement.CheckWater | bool | ctx.SetReturn(...) | ctx.Return |
Items.GetItemInLoadout behaves a little differently: the Pre SetReturn(item) is only used when the hook result is Stop or CancelOriginal, and the Post Return object is only valid during the callback - keep the item's address instead if you need it later.
Every other hook has no return value - use SetHookResult(HookResult.CancelOriginal) when you need to stop the original call.