Reputation: 1697
I am interfacing with a hardware device that runs C++ code and sends live data almost 10 times per second to the iOS device.
I have a Swift method like this:
func m16b_to_mE0(_ pointer: UnsafePointer<m16bytes_t>) -> UnsafePointer<metrics_E0>? {
return UnsafeRawPointer(pointer).bindMemory(to: metrics_E0.self, capacity: MemoryLayout<metrics_E0>.size)
}
Where m16bytes_t
is
typedef uint8_t m16bytes_t[16];
And metrics_E0
is
struct metrics_E0 {
uint8_t tag;
uint8_t hr;
uint16_t c_speed;
uint16_t c_max_speed;
uint16_t c_met_power;
uint16_t c_speed_intensity;
uint16_t c_hr_exertion;
uint8_t hr_avg;
u3bytes_t c_acc_met_power; //typedef uint8_t u3bytes_t[3];
};
The above m16b_to_mE0
method is called almost 10 times per second, for about two hours, more or less.
My question is: is it required to deallocate / deinitialize memory for each UnsafeRawPointer
after bindMemory
to metrics_E0
? If yes, how?
What happens if I don't take care to manually deallocate / deinitialize the UnsafePointer
type from the memory?
Upvotes: 0
Views: 253
Reputation: 32879
bindMemory
doesn't change the ownership of the allocated memory, it's goal is to allow you to peak at the contents of the memory. Unless specified in the documentation of the C++ library that you need to manually release the received pointer, then you should not need to worry about this.
You can do some memory profiling if you want to be sure, and to monitor the memory usage of your application. Or, if you have access to the C++ code, you could set a breakpoint on the m16b_to_mE0
function and go through the stacktrace until you reach the C++ zone, and check what happens later with the pointer that was sent to your method.
Note that releasing the memory of that buffer might require some library dedicated functions for deallocations, instead of the standard ones, however this should be specified in the library documentation.
Upvotes: 1