Lifetimes
In Fahrenheit: with the SDK switched to Fahrenheit (SetTemperatureUnit() and its counterparts, see Temperatures in Fahrenheit), every temperature on this page is read and written in Fahrenheit, and every difference in Fahrenheit degrees; the samples are unchanged.
Overview
Three questions decide whether an application leaks, crashes on the way out, or reads a frame that is no longer there:
- who owns a camera, and what closing it waits for;
- whether a frame is yours or borrowed, which differs between the push path and the pull path in every binding;
- what hangs off a camera and therefore has to go before it does.
The answers are the same in all five surfaces. What differs is how much of it the language enforces and how much it merely documents, which is the table at the end.
What owns a camera
// A unique_ptr. Destroying it disconnects; there is no separate // disconnect call. std::unique_ptr<Imager> mine = Imager::Create(SimulatedConfig{});
/* An opaque handle, and one explicit destroy per create. */ optris_sdk_imager *mine = NULL; optris_sdk_simulated_config sim; optris_sdk_simulated_config_init(&sim, sizeof(sim)); optris_sdk_imager_create_simulated(&sim, &mine); optris_sdk_imager_destroy(mine);
// IDisposable, and the asynchronous form is the one to prefer: see // below for what Dispose() blocks on. await using ThermalCamera mine = ThermalCamera.OpenSimulated();
# A context manager, and close() for the cases that have no block. with optris_sdk.Camera.simulated() as mine: pass
// Dropped at the end of scope. There is no close() to forget. let mine = Camera::simulated(&SimulatedConfig::new())?;
The SDK owns no camera on your behalf. There is no registry, no singleton and nothing to look a camera up in afterwards, which is why a handle that goes out of scope without being closed is the one way to leak one.
A camera is also claimed exclusively across the machine for as long as it is open, so a leaked handle is not only memory: it keeps every other process out. See Device Communication.
Closing a camera stops it
Closing is not a free operation and it is not asynchronous. In order, it stops the stream, waits for any callback already running to return, joins the camera's threads, releases buffered frames and drops the claim. When it returns, nothing of yours can be called again.
That is the guarantee worth having, because it is what makes it safe to destroy whatever your callbacks write into immediately afterwards. It is also why the call blocks, and why .NET offers an asynchronous form: DisposeAsync() does the same work without holding the calling thread, which on a user-interface thread is the difference between a pause and a freeze. Dispose() is correct and synchronous; prefer await using.
Python's close() and Rust's Drop block in the same way, and C++'s destructor and C's optris_sdk_imager_destroy() likewise. optris_sdk_imager_destroy() additionally cannot fail and accepts anything, including a handle it has already been given, which is what makes it safe to call from a finaliser; the .NET package relies on exactly that.
A frame from a callback is borrowed
A frame handed to a callback is valid until that callback returns. The SDK reuses the memory immediately afterwards, so a reference kept past the return goes on looking valid and quietly starts reading the next frame's data.
imager->SetThermalCallback([](const ThermalFrame &f) { // Valid here and nowhere else. Copy what you need. float centre = f.GetTemperature(f.GetWidth() / 2, f.GetHeight() / 2); });
/* The frame pointer is borrowed: do NOT call * optris_sdk_frame_free() on it. A pulled frame is the other case. */ static void OnThermalFrame(const optris_sdk_frame *f, void *user) { optris_sdk_frame_info info; optris_sdk_frame_info_init(&info, sizeof(info)); optris_sdk_frame_get_info(f, &info); (void)user; }
def on_frame(frame): # The package invalidates this object when the handler returns, so # using it afterwards raises rather than reading freed memory. # to_numpy() already returns a copy; clone() gives an owned frame. keep = frame.to_numpy() camera.on_thermal_frame(on_frame)
camera.on_thermal_frame(move |frame| { let pixels = frame.data()?; // fine, inside the callback escaped = Some(pixels); // does not compile })?;
Rust is the only one of the five that refuses this at compile time. The frame carries a lifetime, so a slice taken from it cannot escape the closure. Everywhere else the rule is documented and not enforced, which is why it is worth stating once rather than per page.
A pulled frame is owned
A frame you asked for is yours, and it outlives the call that produced it. That is the whole difference from the section above, and it is the one place where C and the three bindings have an obligation C++ does not.
// A value. Nothing to release. ThermalFrame mine = imager->AcquireFrame(1000ms);
/* Yours, so free it. This is the half a callback must not do. */ optris_sdk_frame *mine = NULL; optris_sdk_imager_acquire_frame(imager, 1000, &mine); optris_sdk_frame_free(mine);
// Yours, so dispose it. `using` on every frame is the whole // discipline; see below for what happens when you do not. using ThermalFrame mine = await camera.AcquireFrameAsync( TimeSpan.FromSeconds(2), CancellationToken.None);
# Owned, and a context manager, so a `with` closes it. with camera.acquire(5000) as mine: celsius = mine.temperatures()
// Owned, and dropped at the end of scope. let mine = camera.acquire_frame(5000)?.expect("a frame"); let info = mine.info()?;
In .NET, not disposing one is not a crash and it is not free either. Every native handle in the package is a SafeHandle, so a frame nobody disposed is still released, eventually, by the finaliser rather than never. What the collector cannot see is how much native memory the frame is holding: the package registers no GC pressure for it, so at 32 frames a second the collector has no reason to run often enough and memory climbs while nothing looks wrong. That is the mechanism behind the symptom, and using is the whole fix.
Pixels are a view, not a copy
The pixel accessor hands back the SDK's own memory. Nothing is copied, which is the point: at 32 Hz on a 640x480 sensor, copying every frame is 19 MB/s of pure overhead.
It is valid for exactly as long as the frame it came from, and no longer. On a borrowed frame that is until the callback returns; on an owned frame, until it is released.
std::span<const int16_t> pixels = frame.GetData();
const int16_t *pixels = NULL; size_t count = 0; optris_sdk_frame_get_data(frame, &pixels, &count);
ReadOnlySpan<short> pixels = frame.Pixels;
# A memoryview over the SDK's buffer. to_numpy(celsius=False) is the # same bytes without a copy. pixels = frame.samples()
let pixels: &[i16] = frame.data()?;
Two of the five enforce it. C# makes the span a ref struct, so it cannot be stored in a field, and Rust ties it to the frame's lifetime. C, C++ and Python hand back something that can be kept and must not be.
The values are the SDK's internal format, not degrees: Reading temperatures out of a frame has the conversion and the three things it refuses.
Keeping a frame's data
Three ways, in order of preference, and the order is the same in every binding: reuse a buffer you own, allocate per call, or clone the frame.
std::vector<float> buffer(frame.GetPixelCount()); frame.CopyTemperaturesTo(buffer); // best in a loop ThermalFrame copy = frame; // an independent frame
float *buffer = (float *)malloc(pixels * sizeof(float)); size_t written = 0; optris_sdk_frame_read_temperatures(frame, buffer, pixels, &written); /* optris_sdk_frame_clone() for an independent frame, which then has * to be freed like any other owned one. */
// Best in a loop: rent a buffer once and reuse it. float[] buffer = new float[camera.Width * camera.Height]; frame.CopyTemperaturesTo(buffer); // Convenient, allocates per call. float[] temperatures = frame.ToArray(); // An independent frame, for handing to something whose lifetime you // do not control. using ThermalFrame copy = frame.Clone();
celsius = frame.temperatures() # a list, copied owned = frame.clone() # an independent frame owned.close()
let celsius: Vec<f32> = frame.temperatures()?; // `to_owned()` is on the BORROWED view, `Frame<'_>`, because that is // where the lifetime problem is. On a frame you already own -- // anything `Camera::acquire_frame()` handed you -- borrow it first // with `as_frame()`. let owned = frame.as_frame().to_owned()?;
A clone is an independent frame with its own lifetime, so it is the answer whenever the thing receiving it outlives the frame: a queue, a worker thread, a user interface.
Metadata outlives its frame
The metadata is a value, not a view, in every binding: a readonly struct in .NET, a plain struct in C and C++, a record in Python, a Copy type in Rust. So it can be kept after the frame it came from has gone, and keeping it is the cheap way to remember what a frame was without keeping the frame.
// A copy, deliberately: the value survives the frame. const optris::sdk::FrameMetadata meta = frame.GetMetadata(); std::println("frame {} at {} us", meta.sequence, meta.timestamp_us); // box_temp_known is the "reported at all" half: some cameras cannot // report their internal temperatures, and 0.0 is not an answer. if (meta.box_temp_known) { std::println("housing {:.1f} C", meta.box_temp_c); } else { std::println("housing not reported by this camera"); }
/* The info struct is a value, deliberately: it survives the frame. */ optris_sdk_frame_info info; optris_sdk_frame_info_init(&info, sizeof(info)); optris_sdk_frame_get_info(frame, &info); printf("frame %u at %llu us\n", info.sequence, (unsigned long long)info.timestamp_us); if (!info.flag_open) { /* The internal shutter was closed: the sensor was looking at the * shutter, not at the scene. */ }
FrameMetadata meta = frame.Metadata; Console.WriteLine($"frame {meta.Sequence} at {meta.Timestamp}"); // `HousingTemperature` is `float?`: null means the camera reported no // housing reading, which is a different thing from a housing at 0 C. // Some cameras cannot report their internal temperatures at all. Console.WriteLine(meta.HousingTemperature is float housing ? $"housing {housing:F1} C" : "housing not reported by this camera"); if (!meta.IsFlagOpen) { // The internal shutter was closed: the sensor was looking at the // shutter, not at the scene. These pixels are not a measurement // of anything in front of the camera. // // On a LIVE CAMERA this never happens, and that is correct rather // than broken -- such frames are not delivered at all. Use // OnShutterState below to follow the shutter. }
# The attributes read through a copied record, so they survive the # frame; frame.samples() does not. print(f"frame {frame.sequence} at {frame.timestamp_us} us") # box_temp_c is None when the camera reported no housing reading, # which is a different thing from a housing at 0 C. if frame.box_temp_c is not None: print(f"housing {frame.box_temp_c:.1f} C") else: print('housing not reported by this camera')
// FrameInfo is Copy, deliberately: the value survives the frame. let info = frame.info()?; println!("frame {} at {} us", info.sequence, info.timestamp_us); // None means the camera reported no housing reading, which is a // different thing from a housing at 0 C. match info.box_temp_c { Some(housing) => println!("housing {housing:.1} C"), None => println!("housing not reported by this camera"), }
That is the asymmetry to remember: the metadata value survives, the pixels do not.
Handles reached through a camera
Anything an accessor hands back refers to the camera and is valid only for as long as the camera is. A process interface, a recorder, a regions handle, a canvas: none of them owns the camera and none of them keeps it alive.
So the order matters, and it is the one order that is not obvious from the types:
| Release this | before this |
|---|---|
| a process interface | the camera it came from |
| a frame | the camera that produced it |
| a recorder's recording | the camera, by stopping it |
| a log handler | whatever it writes into (Logging) |
.NET reports the wrong order as ObjectDisposedException rather than punishing it, which is a diagnosis rather than a crash, but it is still the wrong order.
A configuration record is the exception, and deliberately so. It owns unmanaged memory of its own, so it has to be released, and it may outlive the camera it was read from, because releasing it never touches that camera. That is what lets a setup be read from one camera and applied to another.
What a callback may not do
Every binding has the same three rules, for the same reason: the thread calling you is a thread the SDK needs back.
- Do not close the camera from inside a callback. Closing waits for callbacks in flight, so from inside one it waits for itself. C++ says so; Python refuses rather than hangs, and so do
stop(),reconnect(),set_operation_mode()and the network-configuration write, each of which has to drain the stream. - Do not let an exception escape. There is no frame of yours above it: the caller is C++. Every binding catches and discards at the boundary rather than letting it unwind, because that would be undefined behaviour, and Python additionally has nowhere to report it except
stderr. Catch what you expect inside the handler. - Return promptly. A blocked callback holds up the stream behind it. In Python it also holds the GIL, so it stops every other thread in the interpreter and not only the SDK's.
The log handler is the one callback that does not follow the first of these, because it can arrive on your own thread; Logging states its contract separately for that reason.
Closing order
At the end of a program, in this order:
- Clear the log handler, if one is installed, before destroying whatever it writes into. The SDK keeps logging while it closes cameras (Logging).
- Stop and close every camera. This is what joins the threads and releases the claims, and it is the step a killed process skips, which on some Xi models leaves the device unusable until it is replugged ("No device found" after abrupt shutdown (Xi series, Linux)).
- Then let your own objects go. Not before: a handler the SDK can still reach, writing into something already destroyed, is a crash during shutdown, which is the least diagnosable kind.
A signal handler that sets a flag, and a main loop that performs the three steps above, is the whole pattern. Doing any of it from inside a callback is the case the section before this one is about.
What each language enforces, and what it only documents
| C++ | C | C# | Python | Rust | |
|---|---|---|---|---|---|
| camera ownership | unique_ptr |
one destroy per create |
IDisposable |
context manager | Drop |
| closing is asynchronous | no | no | yes, DisposeAsync |
no | no |
| a missed close is recovered | destructor | never | finaliser, through SafeHandle |
interpreter exit | Drop |
| a pulled frame has to be released | no, a value | yes | yes | yes, or with |
no, Drop |
| borrowed pixels cannot escape | documented | documented | compiler | raises after the handler | compiler |
| a wrong release order says so | no | no | ObjectDisposedException |
raises | will not compile |
| closing from a callback | documented | documented | documented | refused | documented |
C is the one row with a "never", and that is not a gap in the binding: there is no destructor and no finaliser, so a handle dropped on the floor is leaked for the life of the process, along with the camera's claim. Every _create has exactly one _destroy, and every _acquire_frame exactly one _frame_free.