Skip to content

Language bindings for Python, C, Julia, Java and C# with SWIG - #816

Draft
joakimono wants to merge 59 commits into
feature/linux-aarch64from
spike/swig-bindings-v2
Draft

joakimono wants to merge 59 commits into
feature/linux-aarch64from
spike/swig-bindings-v2

Conversation

@joakimono

@joakimono joakimono commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Draft. Stacked on #814. This PR targets feature/linux-aarch64, so the macOS and ARM Linux platforms are available for packaging. It also contains the commits of #815, which drop out of this diff once #815 has merged.

Language bindings for libcosim in Python, C, Julia, Java and C#, all generated with SWIG 4.4.1 from one shared interface (bindings/swig/cosim.i). They are meant to replace the hand-maintained libcosimc and libcosimpy.

Commits, in order

  1. Fixes (8 commits, = Fix leaks and crashes in config parsing and state (de)serialization #815). Leaks and crashes in config parsing and state (de)serialization.
  2. API changes to libcosim (14 commits, each with tests), and one commit that skips the new SSP loader cases on platforms without x86 FMU binaries, like the cases Add 64-bit ARM Linux support #814 skips.
    • Breaking:
      • variable_causality and variable_variability become scoped enums.
      • Config parsers throw cosim::error with error codes.
    • libzip is linked statically. Its DLL zip.dll clashed with the JVM's own zip.dll.
    • Additive:
      • one-call loaders for OSP and SSP, with load options;
      • plain-value real-time accessors;
      • vector- and sample-returning observer getters;
      • add_fmu(), get_simulators();
      • non-blocking start_simulation() / get_status();
      • Boost-free log level control;
      • export_current_state_bytes() / import_state_bytes().
  3. Bindings (bindings/swig/), with CI and release workflows.
    • Python: an abi3 wheel per platform, with a thin Pythonic layer on top.
    • C: a Conan package libcosim-c.
    • Julia: a Libcosim package, with binaries as Pkg artifacts.
    • Java: a JAR.
    • C#: a NuGet package.
    • The packages include the proxyfmu executable.
    • The C API is checked against a reference header, and SWIG fails the build on identifiers that are keywords in any target language.
    • Docs per language, a conformance spec, and a migration guide for libcosimpy.

Testing

  • Linux (GCC 14): 43 tests (libcosim, plus the Python, C, Julia, Java and C# tests).
  • Windows (MSVC): 44 tests, including libcosimpy's own test suite running on the new bindings.
  • The core changes compile without warnings under clang-19 with -Werror.
  • Not built on macOS or ARM Linux yet. The packaging matrices for those platforms are a follow-up.

Open before this leaves draft

🤖 Generated with Claude Code

https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu

joakimono and others added 30 commits November 20, 2026 19:58
The DOMLSParser created in osp_config_parser and in
extended_model_description was never released, leaking the parser and
the whole parsed DOM document on every load_osp_config() call. The
osp_config_parser constructor also created a DOMLSOutput and a
StdOutFormatTarget that were never used nor freed.

Release each parser with a final_action declared after the
XMLPlatformUtils::Terminate() guard, so it runs before termination, and
remove the unused output objects.

Valgrind on cpp_osp_config_parser_test: 37,216 bytes definitely lost
and 742,940 bytes indirectly lost before, 0 after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ecco_algorithm_from_system_structure_test streamed path::c_str() to
std::cout. On Windows that is a const wchar_t*, and since C++20
operator<<(ostream&, const wchar_t*) is deleted, so the test does not
compile with MSVC and /std:c++20 (before C++20 it printed a pointer
address). Use path::string().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libcosim links libcbor::libcbor publicly, so the exported target lists it
in its link interface, but libcosim-config.cmake did not look for it.
Any CMake project using find_package(libcosim) therefore failed with
"The link interface of target libcosim::cosim contains libcbor::libcbor
but the target was not found", unless it found libcbor itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reading malformed CBOR (e.g. a truncated or corrupted state file) could
crash: the reader callbacks read the top of empty state stacks, and they
threw C++ exceptions through libcbor's C decoder.

The callbacks now record the first error instead of throwing (and do
nothing afterwards); it is rethrown once decoding has stopped. Items
outside any map or array, empty input and incomplete data are errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
- CBOR writer: the byte items of FMU states were pushed into arrays
  without cbor_move(), and tagged signed integers kept an extra
  reference to the wrapped item, so every exported state leaked.
- A failed import could leak simulator states: slave_simulator kept the
  slave state it had imported if the rest of its data was invalid, and
  execution did not release an imported state that failed to restore.

Found with valgrind on save_state_test (now clean, including truncated,
corrupted and random state data).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
save_state_test now reads truncated, bit-flipped and random CBOR state
data and imports whatever still decodes. Each case must end in an
exception, never a crash, and the valid state must import afterwards.
On master this test crashes (segmentation fault in the CBOR reader).
Valgrind reports no leaks with the fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
The Windows CI builds with MSVC 19.50 (Visual Studio 2026, on the
windows-2025 runners) stopped with D8040 (error creating or
communicating with child process) while compiling libcosim. The likely
cause is guarded<Sig, F>, a partial specialization that deduces a
parameter pack from a function pointer template argument. Each callback
is now a captureless lambda that runs the reader function through
guarded().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
The reader added entries with put() and put_child(), which parse the
key as a path: a key with '.' became nested entries, and an empty key
(or one that starts or ends with '.') failed an assertion in
Boost.PropertyTree in debug builds. Invalid state data can contain such
keys, and save_state_test aborted in Debug. Entries are now looked up
and added by their exact key. Keys written by libcosim do not contain
'.', so valid state data reads as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
Invalid OSP and SSP configurations were reported as plain
std::runtime_error (or boost::property_tree::xml_parser_error for
unreadable SSD/SSV files), so callers could not tell the error kind
apart and language bindings could not expose an error code.

Throw cosim::error instead:
- errc::bad_file for invalid, unreadable or missing files and invalid
  values (validation failures, unknown algorithm or function types,
  invalid step size, start time after end time, ...)
- errc::invalid_system_structure for inconsistent connections, power
  bonds and unknown components/connectors

cosim::error derives from std::runtime_error, so existing catch clauses
keep working. Throws of std::invalid_argument / std::out_of_range (for
example in scenario_parser) are left unchanged, as converting them
would break callers catching those types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both were unscoped enums, which put their enumerators (input, output,
parameter, local, constant, fixed, tunable, discrete, continuous, ...)
directly into the cosim namespace and allowed implicit conversion to
int. Language bindings consequently exposed them as bare module-level
names (e.g. libcosim.input). variable_type is already an enum class.

BREAKING CHANGE: code that uses the bare enumerator names (cosim::input,
cosim::output, ...) or relies on implicit conversion to int must use
the qualified names (cosim::variable_causality::input, ...) and an
explicit static_cast. Code already using qualified names is unaffected.

Inside libcosim, only two switch statements (override_manipulator,
scenario_parser) used bare names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libzip is only used internally (src/cosim/utility/zip.cpp), but was
built as a shared library like all other dependencies. On Windows its
DLL is named zip.dll, the same name as the JVM's own zip.dll: a JVM
loads its zip.dll at startup, and when cosim.dll is loaded later it is
bound to the JVM's module, which lacks libzip's functions. libcosim
therefore could not be loaded into a JVM on Windows (UnsatisfiedLinkError:
The specified procedure could not be found), affecting any Java binding.

Build libzip as a static library, so no zip.dll is shipped. On Linux
libcosim.so no longer depends on libzip.so; all tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Real-time settings and measurements were only reachable through
get_real_time_config() / get_real_time_metrics(), which return structs
of std::atomic members. Those cannot be copied, nor used from C or
from language bindings.

Add thread-safe accessors with plain types on execution:
set_real_time_simulation / is_real_time_simulation,
set/get_real_time_factor_target, set/get_steps_to_monitor,
get_rolling_average_real_time_factor and
get_total_average_real_time_factor. The setters reject non-positive
values. They mirror what libcosimc already offers, so that logic no
longer needs to live in each wrapper.

The existing struct-based accessors are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add get_real/get_integer/get_boolean/get_string overloads that take a
std::vector of value references and return the latest observed values
in a new vector. They need no pre-sized output buffers, which makes
them simpler to use from C++ and directly usable from language bindings
(the gsl::span output parameters of the existing overloads are not).

get_boolean goes through a plain buffer since std::vector<bool> is not
contiguous. The span-based overloads are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_real_samples() and get_integer_samples() fill three caller-provided
output spans (values, step numbers, times) and return the number of
samples written. Add overloads that take a maximum sample count and
return a time_series_samples<T> holding three equally long vectors.

These need no pre-sized output buffers and are directly usable from
language bindings. The span-based overloads are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Creating a runnable execution from a configuration file took several
steps that every client (cosim-cli, libcosimc, language wrappers) had to
repeat: load the configuration, create the algorithm it specifies
(selecting fixed-step or ECCO from a std::variant), create the
execution, and inject the system structure and initial values.

Add:
- configured_execution (execution.hpp): the execution, its entity index
  maps and the configured end time
- load_execution_from_osp_config(path, resolver = nullptr)
- load_execution_from_ssp(path, algorithm = nullptr, parameterSet = "")
  which uses the given algorithm, else the SSP's default experiment,
  and reports a missing algorithm or unknown parameter set as
  cosim::error with errc::bad_file

Existing functions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
last_value_observer, time_series_observer, file_observer,
override_manipulator, scenario_manager, fixed_step_algorithm and
ecco_algorithm publicly declared their overrides of the observer,
manipulator and algorithm interfaces (simulator_added, step_complete,
step_commencing, add_simulator, do_step, ...). These are callbacks
invoked by the execution through a base-class pointer, not user API,
but they cluttered the public interface of each class and had to be
hidden one by one in language bindings.

Declare them private. Virtual dispatch through the base class is
unaffected, and the user-facing methods (getters, start_observing,
override_*_variable, load_scenario, set_stepsize_decimation_factor,
add_power_bond, ...) stay public.

BREAKING CHANGE: C++ code calling these interface methods directly on
a concrete type (e.g. myLastValueObserver.step_complete(...)) must call
them through the base class (observer&, manipulator&, algorithm&).
Nothing in libcosim or its tests does so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
load_execution_from_osp_config() and load_execution_from_ssp() could not
be used by cosim-cli or libcosimc, which need to override the start
time, choose the number of worker threads, and pass their own (caching)
model URI resolver.

Replace the individual optional parameters with an
execution_load_options struct:
- start_time: overrides the configured start time
- worker_thread_count: for the fixed-step/ECCO algorithm the OSP loader
  creates
- model_resolver: used by both loaders (default resolver if null)
- algorithm: overrides the configured algorithm (both loaders)
- parameter_set: SSP parameter set (default values if empty)

The loaders were added on this branch and are not released, so the
signature change breaks no users.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two conveniences that libcosimc implements on its own and libcosimpy
users rely on:

- add_fmu(execution, fmuPath, instanceName, stepSizeHint, resolver):
  loads an FMU through a model URI resolver (default resolver if null)
  and adds an instance of it, replacing the resolver/lookup_model/
  instantiate/add_slave sequence (cosim_local_slave_create +
  cosim_execution_add_slave in libcosimc).
- execution::get_simulators(): names and indexes of all simulators
  (simulator_info), for any execution, not only those created from a
  configuration (cosim_execution_get_slave_infos in libcosimc).

Adds execution_api_test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libcosimc implements a non-blocking "start" with its own thread around
simulate_until_async(), plus a status query; libcosimpy builds on both.
Move this into libcosim:

- execution::start_simulation(): runs the simulation on a background
  thread until stop_simulation(). Rejected with errc::invalid_operation
  if a simulation is already running.
- execution::get_status(): thread-safe snapshot (execution_status) of
  current time, state (execution_state: stopped / running / error),
  error code and message of a failed background run, and real-time
  settings and metrics.

Thread safety:
- current_time() reads an atomically published copy of the time, so it
  is safe while a simulation runs on another thread.
- The running flag is set before the thread starts, so a
  stop_simulation() right after start_simulation() cannot be lost.
- is_running() stays true until the background thread has finished its
  last step; simulate_until() and step() are rejected while it runs.
- Destroying an execution stops and joins a background run.

Tests (execution_api_test) cover start/stop/restart, stop right after
start, an error in the background run, and destruction while running;
ThreadSanitizer reports no data races in them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
set_global_output_level() and setup_simple_console_logging() are inline
in cosim/log/simple.hpp and expose Boost.Log types, so they cannot be
used from C or language bindings (libcosimc wraps them itself).

Add cosim/log/level.hpp with an enum class level and two functions
implemented in the library: set_output_level(level) and
setup_console_logging() (idempotent). The existing functions are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The execution state as bytes (CBOR, as written by
serialization::format::cbor), for checkpoints in memory or in files, in a
form the language bindings can pass on (bytes, byte[]).

Unlike export_current_state()/import_state(), whose violated
preconditions abort, these throw cosim::error with
errc::invalid_operation if the execution is not initialized or a
simulation is running, and errc::bad_file for invalid state data.

save_state_test covers the round trip, and truncated, corrupted and
random data (an error, never a crash; valgrind-clean).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
test_add_fmu_and_get_simulators used fmi1/identity.fmu, which only has
binaries for x86 Linux and Windows. It now uses the Feedthrough
Reference FMU, which is built for the platform the tests run on, so the
test also runs on macOS and 64-bit ARM Linux.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
load_execution_from_ssp_test and load_execution_from_ssp_algorithm_test
load the same bundled SSP test data as the other SSP loader cases,
whose FMUs only have binaries for x86 Linux and Windows. Add them to
the list of cases skipped on other platforms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
Generate Python and C bindings with SWIG from one shared interface
(bindings/swig/cosim.i) without modifying the libcosim headers, using
SWIG's experimental C backend for C. Julia uses plain ccall on the
generated C library.

- conanfile.py: new swig_bindings option (off by default) adding
  swig/[>=4.4 <5] as a tool requirement
- CMakeLists.txt: LIBCOSIM_BUILD_SWIG_BINDINGS option
- Python unittest suite, C11 smoke test and Julia smoke test
- bindings/swig/README.md documents results, adaptation counts, SWIG
  and C-backend gotchas, and libcosim-side findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Round 2 of the spike, on top of feature/binding-friendly-api: use the
new native API (real-time accessors, vector-returning observer getters,
time_series_samples, load_execution_from_osp_config/_ssp) instead of
interface-side adapters, and add cosim::filesystem::path typemaps for
Python (str / os.PathLike) and C (const char*).

Result: interface adapters 13 -> 7, glue 2 -> 0, cosim.i 604 -> 468
lines. Python (11 tests), C and Julia smoke tests pass; the C smoke test
is valgrind-clean (0 bytes definitely lost, previously 960 from the
Xerces leak). The README documents the re-measurement, what remains and
why, and new findings (notably borrowed member getters in C).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The observer, manipulator and algorithm interface overrides are private
in libcosim's concrete classes, so SWIG no longer sees them. %ignore
lines 79 -> 59, cosim.i 468 -> 444 lines. All Python, C and Julia tests
pass; the C smoke test is valgrind-clean. README updated, including why
the header directory split was not done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Map cosim::time_point and cosim::duration to integer nanoseconds in
Python and C, the unit used by libcosimc (cosim_time_point,
cosim_duration) and libcosimpy, instead of double seconds. Integer
nanoseconds are exact and match the existing APIs.

Seconds remain available for convenience:
- to_nanoseconds(seconds) / to_seconds(nanoseconds) helpers
- get_times_seconds() and get_end_time_seconds() next to get_times()
  and get_end_time()

Python rejects float time values with a TypeError pointing to
to_nanoseconds(), instead of truncating them to nanoseconds as
libcosimpy does (a float is almost always meant as seconds).

Also adapt to execution_load_options: setters for its std::optional
members, and in C a NULL options pointer means default options.
Fixed-width integers keep their int64_t name in the C header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Close the remaining functional gaps to libcosimc in the bindings:
- add_fmu() and execution::get_simulators()
- execution::start_simulation() / get_status() (execution_status,
  execution_state)
- ecco_algorithm with ecco_algorithm_params and add_power_bond()
  (single constructor; C factory cosim_ecco_algorithm_create)
- cosim/log/level.hpp (set_output_level, setup_console_logging),
  replacing the binding-side log adapter

Struct members of time type (execution_status::current_time,
ecco_algorithm_params::step_size, ...) map to int64 nanoseconds via
%naturalvar. The C backend uses the fully resolved std::chrono type
names for these, so the time typemaps are registered for those too.

compactdefaultargs copies default argument expressions such as
duration::zero() into wrappers outside namespace cosim; a using
declaration makes them resolve.

Python tests cover all of it, including ECCO built entirely in code
(note: power-bond "causality" attributes in OSP files describe the
bond, not the FMU variables). The C smoke test covers add_fmu,
get_simulators and start/stop/status, valgrind-clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Before, struct members of class type and container elements were
returned as pointers into the parent object, in both C and Python:
- C: deleting such a pointer was a double free, and keeping it after the
  parent was deleted a use after free.
- Python: `exe.get_model_description(i).variables` pointed into a
  temporary that was already destroyed; iterating it read freed memory
  (std::bad_alloc, or worse).

Now every returned object is owned by the caller:
- COSIM_RETURN_COPIES: references to selected types (variable
  descriptions, variable ids, simulator infos, capabilities, vectors of
  variable descriptions) are returned as owned copies, in Python and C.
- COSIM_MEMBER_BY_VALUE(_RW): class-type struct members are returned by
  value. Python uses %naturalvar (plus the copies above); C, whose
  backend ignores %naturalvar, gets get_<member>() / set_<member>()
  functions returning owned copies.
- C: libcosimc-style cosim_last_error_code(), cosim_last_error_message()
  (owned copy) and cosim_clear_last_error(), since SWIG's
  cosim_SWIG_CException_msg_get() returns a borrowed pointer.
- C: the ownership and error rules are written at the top of the
  generated header.

Also fixes a bug in SWIG's C backend: its default 'throws' typemaps (used
by std::vector get() for std::out_of_range) record the error but do not
return, so the wrapper used an uninitialised result. Overridden to
return; an out-of-range index is now an error, not a crash.

Julia: the smoke test wraps every returned object in a handle with a
finalizer and does no explicit deletes; all 7 handles are finalized by
the GC, in arbitrary order, without double frees.

Tests: Python 17 (new regression test for members of temporaries,
valgrind-clean), C smoke test valgrind-clean (owned copies,
out-of-range), Julia smoke test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Pin SWIG to exactly 4.4.1 (Conan and CMake): the C backend is
  experimental and makes no compatibility promises between versions.
- Register the binding tests with CTest: swig_python, swig_c_smoke,
  swig_julia_smoke (if Julia is installed) and swig_c_api_reference.
- swig_c_api_reference: the generated C header must match the committed
  reference (bindings/swig/c/reference/cosim_c_wrap.h), so any change to
  the C API - from libcosim, the interface files or a SWIG upgrade - is
  deliberate and reviewed. Update with the update_swig_c_api_reference
  target. Container element types that are int64_t now appear as int64_t
  (not long / long long), so the header is the same on all platforms.
- Windows: Python >= 3.8 ignores PATH when loading the DLLs of an
  extension module, so the package registers its own directory and
  LIBCOSIM_DLL_DIRS with os.add_dll_directory(). Warning options for
  generated code are set per compiler (MSVC does not take -w).
- New workflow ci-swig-bindings.yml: builds with the bindings and runs
  the full test suite through `conan build` on Ubuntu 24.04 and
  Windows 2025.

Verified locally on Linux with the workflow's command: 40/40 tests pass
(36 libcosim + 4 bindings). The Windows job has not been run yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
joakimono and others added 27 commits November 20, 2026 19:58
bindings/swig/python/compat/libcosimpy: a pure-Python drop-in for
libcosimpy's public modules (CosimExecution, CosimObserver,
CosimManipulator, CosimSlave, CosimAlgorithm, CosimEnums, CosimLogging,
CosimConstants), implemented on the SWIG module instead of ctypes on
libcosimc. It reproduces libcosimpy's behaviour: integer nanosecond
times, EccoParams durations in seconds, libcosimc's numeric error codes
and execution states, names and strings as bytes, its exception types
for invalid input, and libcosimc's power-bond argument order.

libcosimpy's own test suite, unchanged, passes against it: 51 of 52.
The remaining test asserts the order of slave_infos(), which in
libcosimc is the iteration order of a std::unordered_map (implementation
defined, so not portable even for libcosimc); the layer returns
simulators in index order. The suite can run under CTest by setting
LIBCOSIM_SWIG_LIBCOSIMPY_DIR to a libcosimpy checkout (test
swig_libcosimpy_compat, with that one test excluded).

Known differences, documented in the code:
- real_time_factor_target(<= 0) succeeds but is ignored (libcosimc
  accepts any value; libcosim now rejects non-positive targets).
- libcosimpy's CosimErrorCode enum is out of sync with libcosimc (no
  SIMULATION_ERROR; ZIP_ERROR = 11 where libcosimc has 12); the layer
  returns libcosimc's numeric codes, as libcosimpy does today.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A third SWIG backend, to confirm that the shared interface (cosim.i)
carries over unchanged: the only change to it is hiding operator== and
operator!= for Java (proxies compare by identity).

bindings/swig/java/cosim_java.i (~120 lines) adds only Java-specific
parts: time as long nanoseconds, paths as String, owned copies for
returned references, and libcosim.CosimException carrying the
cosim::errc code. Generated classes are in package `libcosim`, the
native library is `cosim_java`. Vectors implement java.util.List, maps
java.util.Map, enums are Java enums.

The JDK comes from Conan (zulu-openjdk/21.0.11) behind a new option
swig_java (default off), so Python-only builds do not download it.
CMake: LIBCOSIM_SWIG_JAVA. The generated and hand-written Java sources
are compiled after SWIG runs (generated file names are not known in
advance).

swig_java_smoke covers error codes, OSP loading, override and last
value, nanosecond times, member copies, add_fmu, get_simulators,
start/stop/status and ECCO from code. The CI workflow enables Java.

Findings: the enumerator variable_type::boolean is a Java keyword and
becomes `_boolean`; with compactdefaultargs Java gets only full
signatures (no default arguments).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Current state (Python, libcosimpy compatibility, C, Julia, Java from one
interface), build and test instructions including the CI command,
round-3 changes and findings, what is not covered yet, and next steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With OUTPUT_NAME cosim, MSVC writes the module's import library as
cosim.lib into libcosim's library directory, which clashes with
libcosim's own cosim.lib (LNK1149). Put it in a separate directory; the
module's import library is never used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
generate() copied the DLLs of all dependencies, including tool
requirements, into the output bin directory. With the JDK as a tool
requirement (option swig_java), its bundled, older ucrtbase.dll and
other runtime DLLs ended up next to every executable and shadowed the
system's Universal CRT, so all tests failed on Windows with
STATUS_ENTRYPOINT_NOT_FOUND (0xc0000139). Iterate over
self.dependencies.host instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- test_file_observer: use a separate execution and release it before the
  temporary directory is removed; Windows cannot delete files the file
  observer still has open.
- Java and Julia tests: put libcosim's runtime directory on PATH. When
  java.exe / julia.exe load cosim_java.dll / cosim_c.dll, Windows does not
  search the DLL's own directory for the libraries it depends on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ownership rule said to free() returned strings. On Windows memory
must be freed by the C runtime that allocated it, and a caller may use a
different one (another compiler, a debug runtime, or Julia, whose
Libc.free uses msvcrt): the Julia smoke test crashed with heap
corruption (0xc0000374) on Windows. Strings must now be released with
cosim_free_string(), which uses the library's own runtime. Header rules,
C smoke test, Julia test and reference header updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fourth SWIG backend. The shared interface (cosim.i) only needed the
operator==/!= exclusion extended from Java to C#.

bindings/swig/csharp/cosim_csharp.i adds the C#-specific parts: time as
long nanoseconds, paths as string, owned copies for returned references
(including C# property getters), and Libcosim.CosimException carrying
the cosim::errc code (raised through a registered callback, as in SWIG's
C# manual). Generated classes are in namespace `Libcosim`, the native
library is `cosim_csharp`. Struct members become C# properties, vectors
implement IList<T>.

The .NET SDK (dotnet) must be installed; there is no Conan package.
Options: Conan swig_csharp, CMake LIBCOSIM_SWIG_CSHARP. The smoke test
is a net10.0 console project compiling the generated and hand-written
sources; swig_csharp_smoke covers the same ground as the Java test.
The test runtime path helper also sets LD_LIBRARY_PATH (DllImport on
Linux). The CI workflow installs .NET 10 and enables C#.

Verified on Windows (MSVC, .NET SDK 10.0.404): 43/43 tests, and on Linux
(GCC, .NET SDK 10.0.404): all 7 binding tests pass.

Findings: the enumerators variable_type::string and
variable_variability::fixed are C# keywords and become string_ and
fixed_.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
variable_type::boolean is a keyword in Java, and variable_type::string
and variable_variability::fixed are keywords in C#, so SWIG renamed them
differently per language (_boolean, string_, fixed_). Rename them once in
the shared interface, identically for all languages:

  variable_type::boolean       -> boolean_value
  variable_type::string        -> string_value
  variable_variability::fixed  -> fixed_value

(Python: variable_type_boolean_value etc.; C:
cosim_variable_type_boolean_value etc.) C++ keeps its names. SWIG now
reports no keyword warnings (314) for Java or C#. The libcosimpy
compatibility layer, the reference C header and a Python regression test
are updated.

Also generate proper Java enums (enums.swg) instead of SWIG's default
"typesafe enum" classes, so they work with switch, EnumSet and EnumMap.
(The Java bindings commit described them as Java enums; that was not the
case until now.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bindings/swig now also builds standalone against the libcosim Conan
package (find_package(libcosim)), so it can move to its own repository.

- C: Conan package libcosim-c (conanfile.py, test_package)
- Python: wheel via scikit-build-core (pyproject.toml)
- Java: JAR with the native libraries, extracted and loaded by NativeLoader
- C#: NuGet package with runtimes/<rid>/native
- Julia: package Libcosim, ccall layer generated from the C header

Each package bundles libcosim and its non-system dependencies
(file(GET_RUNTIME_DEPENDENCIES), RPATH $ORIGIN on Linux).
packaging/build_packages.py builds all packages and tests each with
nothing but the package on the search paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
- build_packages.py: run commands in the Conan environment on Windows
  (cmd quoting), build the wheel for Release only (Visual Studio
  generates all configurations), install the C package to dist/c
- ci-swig-bindings: new job that creates the libcosim package, builds
  and tests all binding packages on Linux and Windows, and uploads them
- README: package sizes on Linux and Windows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
The Julia package no longer bundles the C library in lib/. Instead,
julia/make_artifact.jl packs the library and its dependencies as the
`libcosim_c` artifact for one platform (a tarball and an Artifacts.toml
entry); Pkg downloads it when the package is installed. The entries of
several platforms concatenate into the package's Artifacts.toml, whose
URLs point to the GitHub release of the version.

build_packages.py tests the package as a user installs it: Pkg.develop
into a fresh depot, downloading the artifact from the local tarball.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
- release-bindings.yml (v* tags): wheels with cibuildwheel (manylinux on
  Linux), the C, Java, C# and Julia packages per platform, then PyPI
  (trusted publishing), the OSP Conan remote, and a GitHub release with
  the merged JAR and NuGet package, the Julia artifacts and package
  source, and the C library archives
- merge_packages.py: merges the per-platform JARs, NuGet packages and
  Julia Artifacts.toml entries
- cibw_before_all.py: provides libcosim and SWIG through Conan for
  cibuildwheel
- The Conan toolchain now carries SWIG's location (SWIG_EXECUTABLE,
  SWIG_DIR), so the wheel builds without Conan's environment; FindSWIG in
  module mode, as a failed config-mode search would reset SWIG_DIR

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
A new build step (swig_keyword_check) runs SWIG for Python, Java, C# and
C, built or not, and fails if SWIG renamed an identifier because it is a
keyword in that language (warning 314): the fix is a shared %rename in
cosim.i, so that all bindings keep the same names.

Also makes the binding tests run in a standalone build without Conan's
run environment: the test helper adds the bindings' output directory and
the Conan runtime directories to PATH, LD_LIBRARY_PATH and
LIBCOSIM_DLL_DIRS (now also for the Python test), and the C smoke test
gets an RPATH for libcosim's dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
- Build against the released libcosim of the same version
  (libcosim/<v>@osp/stable) by default; LIBCOSIM_REF selects another
  package, e.g. libcosim/<v>@local/testing created from a checkout (CI and
  cibuildwheel do that for unreleased versions)
- Release workflow: runs when libcosim's Conan workflow has succeeded for
  a version tag (so libcosim/<v>@osp/stable exists), builds the tagged
  commit; manual runs can build libcosim from source and then skip the
  libcosim-c upload. Uses the OSP remote credentials of libcosim's own
  workflow. Wheels build libcosim inside the manylinux container, as the
  remote's Linux binaries need a newer glibc.
- README: a developer README for the bindings; the spike report moves to
  docs/spike-report.md as history
- test_spike.py -> test_bindings.py; no more "spike" in interface and
  package headers; cosim.i's header describes the current design

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
With wheel.py-api = "cp310", scikit-build-core builds one abi3 wheel per
platform that works with CPython 3.10 and later: the module is compiled
with Py_LIMITED_API and linked against Python's stable-ABI library.
SWIG's generated code already supports the limited API; the only change
needed was in the path typemap (PyUnicode_AsUTF8AndSize instead of
PyUnicode_AsUTF8, which is limited API only from 3.13). Builds outside a
wheel stay version-specific unless LIBCOSIM_SWIG_PYTHON_SABI is set.

Tested: the same wheel passes the 18 Python tests on 3.10, 3.12 and 3.13;
abi3audit finds no non-abi3 symbols (baseline 3.10).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
python/pythonic.py (installed as libcosim._pythonic) adds to the
generated classes, without replacing anything they provide:

- simulators and variables by name: execution.simulator_index(),
  variables() (dict by name) and variable() (a variable_id);
- type-independent operations dispatching on the variable_id's type:
  set_initial_value(), last_value_observer.value(),
  override_manipulator.override()/reset(), time_series_observer.samples();
- `with exe.running():` starts the simulation in the background and stops
  it (waiting until stopped) at the end of the block, raising CosimError
  if it failed;
- readable reprs with enumerator names.

Adding a name the bindings already define is an error, so a future SWIG
method cannot be shadowed silently. Tested in test_bindings.py
(PythonicTest).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
docs/conformance.md lists what every binding must do (CF-1 ... CF-71:
errors, loading, executions in code, time, variables, running,
observers and manipulators, memory) and which tests cover each item per
language, including the gaps.

Closes most gaps in the priority bindings:
- C (smoke_test.c): version, SSP, load options, end time, initial values
  and last values of all four types, overrides of all four types and
  reset, time series, real-time configuration and its error; still
  valgrind-clean
- Julia (runtests.jl): the same, plus the asynchronous run
- Python: version and a successful SSP load

Remaining: ECCO and the file observer in C and Julia; Java and C# (best
effort) cover the core items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
docs/python.md, c.md, julia.md, java.md and csharp.md: installation, an
example (an FMU, an initial value, a run, reading a value), loading a
configuration, errors and times, plus per-language notes (C: ownership
and error rules; Julia: handles and the artifact; Python: the Pythonic
layer, background runs and time series). Every example was run against
the bindings (C compiled with -Wall -Wextra).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
The compatibility layer now lives in the libcosimpy repository (branch
feature/libcosim-bindings there): libcosimpy becomes a pure-Python
package on the `libcosim` wheel, with an unchanged API and its own test
suite passing. It is removed from libcosim.

The optional CTest test (now swig_libcosimpy) runs a libcosimpy
checkout's tests against these bindings, with the checkout's src on
PYTHONPATH; LIBCOSIM_SWIG_LIBCOSIMPY_DIR selects it.

docs/libcosimpy-migration.md: the two routes (upgrade libcosimpy, or
move to `libcosim`), what changes (errors, names, ECCO durations,
enumerations) and a mapping of libcosimpy's API to libcosim's, with a
side-by-side example (both versions run).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
Multi-config generators put outputs in a per-configuration directory
(output/bin/Release); the test runtime path now includes it, so the C#
smoke test finds cosim_csharp.dll in a standalone Windows build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
execution::export_current_state_bytes() / import_state_bytes() in every
language: Python bytes (bytearray accepted), a ByteVector in C, Java and
C#, and Julia helpers Libcosim.bytes()/byte_vector() for Vector{UInt8}.
The serialization::node versions stay hidden.

Tests (conformance item CF-53) in all five languages: round trip,
continuing with the same results, errors before initialization and for
invalid data. They need an FMU that supports state export,
LIBCOSIM_SWIG_STATE_FMU, which defaults to the Dahlquist reference FMU
in libcosim's build with tests; without it they report themselves as
skipped. (The quarter-truck FMUs advertise state serialization but crash
in fmi2DeSerializeFMUstate.) The C test stays valgrind-clean.

Also: the C API reference header gains the new functions (additions
only), the Julia generator handles unsigned char, and the guides
describe checkpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
When libcosim is built with proxyfmu, proxy FMUs run in a separate
proxyfmu process. The packages now include the proxyfmu executable (and
its libraries) next to the binding's libraries, found from the location
of the proxyfmu client library; BundleRuntime handles executables
(their runtime libraries are bundled, RPATH $ORIGIN on Linux). The
proxyfmu client finds it there with proxy-fmu's change to search next to
its client library (proxy-fmu PR #110).

The bindings recipe gets a proxyfmu option (passed to libcosim, off by
default). A Python test runs a configuration with proxy FMUs from a
directory without the executable (conformance item CF-15), when libcosim
is built with proxyfmu.

Tested on Linux: the wheel, installed in a fresh venv, runs four proxy
FMUs from an unrelated working directory; the Julia package contains the
executable too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
Decided: the published packages support proxy FMUs. The bindings recipe
builds libcosim with proxyfmu by default, so every package contains the
proxyfmu executable; -o "&:proxyfmu=False" builds packages without it.
build_packages.py tests a wheel that contains the executable with proxy
FMUs too.

This needs a proxyfmu release whose client finds the executable next to
its client library (proxy-fmu PR #110, on #108 and #109), required by
libcosim's recipe; with proxyfmu 0.4.3 the executable is not found.

Cost on Linux: about 1.3 MB per package (wheel 7.4 -> 8.7 MB, JAR 7.2 ->
8.6 MB, NuGet 7.4 -> 8.8 MB, Julia artifact 7.1 -> 8.1 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
proxy-fmu #108-#110 are merged and published as new revisions of
proxyfmu/0.4.3@osp/testing, which libcosim's recipe already requires.
Verified: the Python and Julia packages built against it pass their
tests, including proxy FMUs from a fresh venv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
The libcosim changes are now split into a fixes branch from master and
an API branch on top of it. The bindings sit on top of the macOS and
64-bit ARM Linux PRs (#811-#814). Packaging for those platforms is not
added yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
@joakimono
joakimono force-pushed the spike/swig-bindings-v2 branch from 19efdfa to 71aa448 Compare November 20, 2026 19:10
joakimono and others added 2 commits November 20, 2026 20:32
Since libzip/1.11.4 recipe revision f4cee451 on Conan Center, a static
libzip fails to configure against a shared zstd: libzip's CMake links
zstd::libzstd_static, and a shared zstd package only declares
zstd::libzstd_shared. With every other dependency shared, which is
the default, building libzip from source failed. zstd is only used by
libzip, so build it statically too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
With libzip linked statically, libcosim itself needs OpenSSL's
libcrypto.so.3. On the GitHub Ubuntu runners file(GET_RUNTIME_DEPENDENCIES)
found it both in the Conan package and in /lib/x86_64-linux-gnu, and
stopped with "Multiple conflicting paths found". Conflicts are now
collected and treated like other resolved libraries, so the copy in
the dependency directories is bundled (checked locally: the packages
contain Conan's OpenSSL 3.6.5, not the system's 3.5.6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RWDwSfzaJZyQdtQhS6c5Nu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant