ABI & Marshalling

A TonCut Desktop plugin is a Win32 DLL that TonCut Desktop loads into its own process. Every interface on this site is a Delphi safecall interface; this page states the binary rules that a Delphi, C++, or mixed-language plugin must follow to call and implement them correctly.

Platform

TonCut Desktop is a 32-bit (Win32, x86) application, so every plugin must be a 32-bit DLL:

  • Delphi: target platform Windows 32-bit, compiled with dcc32.
  • MSVC and C++Builder: platform Win32 (x86). TonCutPluginSdk.hpp rejects any other target with static_assert(sizeof(void*) == 4, ...).
  • C#: any managed code loaded into the plugin process must be built for PlatformTarget x86; see C# plugins.

A 64-bit DLL cannot be loaded and is reported as a plugin load error.

Records are aligned to 8 bytes, as in Delphi's {$A8} default. TonCutPluginSdk.hpp wraps its declarations in #pragma pack(push, 8).

Type sizes

Use exactly these representations. A mismatch shifts every later argument on the stack and corrupts the call.

PascalC++ (TonCutPluginSdk.hpp)SizeC# equivalent (only inside your own bridge)
Integerint4int
Cardinalunsigned4uint
Int64, TFieldstd::int64_t8long
UInt64, TTcpVersionTTcpVersion (std::uint64_t)8ulong
Word, TRotationunsigned short2ushort
Singlefloat4float
Double, TDateTime, TTcPrice, TTcWeightdouble, TDateTime, TTcPrice, TTcWeight8double
BooleanDelphiBool (unsigned char)1byte (0 or 1), never a 4-byte BOOL
Any enumeration, for example enum : std::uint8_t1byte
TTcpFeatures (std::uint16_t)2ushort
, TOrnaments, TMirrorsstd::uint8_t aliases1byte
WideStringBSTR4IntPtr holding a BSTR
THandle (window handles)HWND4IntPtr
Interfacepointer to the interface struct4IntPtr

A Delphi set is a bitmask in which bit n stands for the member with ordinal n: a set of up to 8 members takes 1 byte and a set of up to 16 members takes 2 bytes. Build in C++ with FeatureMask(feImport) | FeatureMask(feExport); feImport is bit 0 and feAbout is bit 11.

Calling convention

Every interface method is declared safecall. In the binary interface this means:

  • The method is stdcall and returns an HRESULT.
  • A Pascal function result becomes an extra trailing pointer parameter (the "retval"). function GetName(): WideString; safecall; is HRESULT GetName(BSTR* result) in C++.
  • out and var parameters are pointers in C++.
  • A failed HRESULT from a C++ method, or an exception that escapes a Delphi method, is raised as an exception inside TonCut Desktop. TonCut catches it, marks the plugin as failed, disables it, and shows a generic plugin error that names the plugin; the exception text is discarded. Some calls are not protected this way. See Exceptions and failures.

Never let an exception or a failed HRESULT leave a plugin method. Catch everything, return a , and show your own message (owned by the aWindow you received) if the user must see the details. In C++, return S_OK and report the outcome through the out parameter.

Strings

WideString is a COM BSTR, allocated with SysAllocString and freed with SysFreeString on both sides of the boundary:

  • Input strings (const parameters) are owned by the caller. Read or copy them; never free them, and never keep the pointer after the call returns.
  • Output strings (function results and out parameters) are allocated by the callee with SysAllocString; the caller frees them. A C++ plugin returning a string writes a freshly allocated BSTR; toncut::BstrValue::release() hands one over.
  • var strings (for example BackupConfig(var aBackup: WideString)) arrive with a value the callee may replace. Free the old BSTR before storing the new one.
  • When C++ calls a host method that returns a string or an interface through an out slot, set the slot to nullptr first. The Delphi callee releases the previous value of an out slot before writing it.

The entry point is the only exception: its aRegRoot is a plain UTF-16 PChar (const wchar_t*), not a BSTR, and it is valid only during the call. Copy it.

Interfaces and reference counts

Host objects are ordinary reference-counted COM-style interfaces:

  • An interface returned to you (a function result or an out parameter) carries one reference that you own. Release it when you are done; toncut::ComPtr does this in C++, and Delphi interface variables do it automatically.
  • An interface passed to you as a parameter is borrowed for the duration of the call. Call AddRef (in Delphi, assign it to a field) only if you need it afterwards.
  • The plugin object returned from TcpInitializeV2 carries one reference owned by TonCut. TonCut releases it when it unloads the plugin and then calls FreeLibrary immediately, so every object your plugin created must have reached a reference count of zero by then.

What you may keep after a call returns:

ObjectKeep after the call?
ITonCut received by the entry point or InitializeYes, until Finalize.
Collections received by LoadFile (staging) or SaveFile (live data)No.
ISolution and ISolutionSheet received by the result and plot callbacksNo.
ITcEnumExtensionsCallback received by EnumExtensionsNo. Call it only during EnumExtensions.

Interfaces that declare a GUID can be obtained through QueryInterface. ITcPlugin declares none: TonCut never calls QueryInterface on the plugin object, and only AddRef and Release of its IUnknown part are used. Each reference entry shows the interface's IID, its parent interface, its Pascal unit, and its exact vtable order.

Entry point

TonCut resolves exactly one export by name, TcpInitializeV2. A missing export, a failed LoadLibrary, or an exception during the call is reported as a plugin load error, and the plugin is not listed.

The host declares the export as a Delphi function returning an interface:

function TcpInitializeV2(const aRegRoot: PChar; aLanguageId: Integer; aTonCut: ITonCut): ITcPlugin; stdcall;

A Delphi function that returns an interface passes the result as a hidden first argument. In C and C++ the same export is therefore:

extern "C" void __stdcall TcpInitializeV2(
  toncut::ITcPlugin** aResult,   // hidden result: write the plugin here
  const wchar_t* aRegRoot,
  int aLanguageId,
  toncut::ITonCut* aTonCut
);

TonCutPluginSdk.hpp declares the matching pointer type as toncut::TTcPluginInitialize.

TonCut never calls ITcPlugin.Initialize. The entry point must create the plugin object, call Initialize on it with the same arguments, and return it. If it cannot, leave the result nil (nullptr); TonCut then reports a plugin load error.

TcpInitializeV2

function TcpInitializeV2(
  const aRegRoot: PChar;
  aLanguageId: Integer;
  aTonCut: ITonCut
): ITcPlugin; stdcall;
var
  plugin: ITcPlugin;
begin
  Result := nil;
  try
    plugin := TMyPlugin.Create;
    // Initialize takes a WideString; the PChar is copied into it here.
    if plugin.Initialize(aRegRoot, aLanguageId, aTonCut) = cprOK then
      Result := plugin;
  except
    Result := nil;
  end;
end;

MyPlugin in the C++ tab is your class deriving from toncut::ITcPlugin; it must implement QueryInterface, AddRef, and Release itself, as shown in the Quickstart.

Delphi library

A Delphi plugin is a library project. {$E plg} gives the output the .plg extension that TonCut scans for, {$A8} keeps the record alignment of the interface units, and exports publishes the entry point under its plain name.

library MyPlugin;

{$E plg}
{$A8}

uses
  System.SysUtils,
  uITcPluginCommon,
  uITonCut,
  uITcPlugin,
  uMyPlugin in 'uMyPlugin.pas';

function TcpInitializeV2(
  const aRegRoot: PChar;
  aLanguageId: Integer;
  aTonCut: ITonCut
): ITcPlugin; stdcall;
var
  plugin: ITcPlugin;
begin
  Result := nil;
  try
    plugin := TMyPlugin.Create;
    if plugin.Initialize(aRegRoot, aLanguageId, aTonCut) = cprOK then
      Result := plugin;
  except
    Result := nil;
  end;
end;

exports
  TcpInitializeV2;

begin
end.

MSVC module definition file

MSVC decorates a 32-bit __stdcall function as _TcpInitializeV2@16, and TonCut looks up the plain name. Add a module definition (.def) file to the project (Linker > Input > Module Definition File), or an equivalent /EXPORT:TcpInitializeV2=_TcpInitializeV2@16 linker option:

LIBRARY "MyPlugin.plg"
EXPORTS
  TcpInitializeV2

Without it the plugin builds and loads, but TonCut cannot find the entry point and reports a plugin load error. Check the result with dumpbin /exports MyPlugin.plg: the export must be listed as TcpInitializeV2.

Build checklist

ItemDelphiMSVC
Project typelibraryDynamic Library (.dll)
PlatformWindows 32-bitWin32
Output extension{$E plg}Target Extension .plg (and LIBRARY "<name>.plg" in the .def)
Alignment{$A8}TonCutPluginSdk.hpp applies #pragma pack(push, 8)
Export nameexports TcpInitializeV2;.def file EXPORTS TcpInitializeV2
Contract headersunits from include/pascalinclude/cpp/TonCutPluginSdk.hpp

Install the .plg file in the Plugins folder next to TonCut.exe; subfolders are scanned too, and the extension must be lowercase .plg. See Host behaviour for the load sequence.

C# plugins

C# is supported only through a native shim. No TonCut interface is projected to managed code, and a C# assembly cannot be a plugin by itself:

  • The shim is a C++ DLL. It exports TcpInitializeV2, implements ITcPlugin, and owns every TonCut interface pointer and callback.
  • Managed code may do work that needs no TonCut interface, such as parsing or writing a file. The SDK's C# example keeps only CSV parsing, validation, row data, and serialization in managed code; the bridge between shim and managed code is specific to your project.
  • Any managed code loaded into TonCut Desktop runs in the 32-bit TonCut process: build it for PlatformTarget x86.

The type table above lists C# equivalents for data you pass across your own bridge. It does not describe a managed projection of the TonCut interfaces.

C++ names of Pascal overloads

C++ has no overloading in a vtable, so TonCutPluginSdk.hpp gives each Pascal overload its own name. The slots stay in Pascal declaration order.

PascalC++
ITonCut.FormatLength(aValue: Integer; ...)FormatLengthFromInt
ITonCut.FormatLength(aValue: Double; ...)FormatLengthFromExtended
ITonCut.HumanReadableField(aValue: TField; ...)HumanReadableFieldFromInt64
ITonCut.HumanReadableField(aValue: Double; ...)HumanReadableFieldFromExtended
IFormats.IndexOf(const aFormat: IFormat)IndexOfByObject
IFormats.IndexOf(aId: Int64)IndexOfById
IFormats.IndexOf(aList: array of Int64; ...)IndexOfByList
IFormats.IndexOf(const aOtherFormat: IFormat; aSkipId: Int64; var aRotated: Boolean)IndexOfByOther
IFormats.LoadByProject(aProject: IProject; aFormats: IFormats)LoadByProjectInto
IProjects, IMaterials, ISheets, IDevices: IndexOf(object) / IndexOf(aId)IndexOfByObject / IndexOfById
ISheets.IndexOf(const aOtherSheet: ISheet; aSkipId: Int64; var aRotated: Boolean)IndexOfByOther
IProjects.CheckUniqueName(aProject: IProject; ...)CheckUniqueNameByProject
IMaterials.CheckUniqueName(aMaterial: IMaterial; ...)CheckUniqueNameByMaterial
IDevices.CheckUniqueName(aDevice: IDevice; ...)CheckUniqueNameByDevice

Default parameter values do not exist in the binary interface: pass every argument explicitly from C++. A Delphi open array (array of Int64) is passed as a pointer to the first element followed by the highest index (Length - 1).

Contract corrections and gaps

Was this page helpful?