smart pointer to manage socket file descriptor - sockets

A smart pointer clears the memory if the pointer gets out of scope. I wanted to adapt this to a file descriptor, like a socket. There you need a user defined deleter, because close() is the function to free the file descriptor (fd) resources.
I found this useful page, unfortunately, most approaches did not work for me. Below is a working solution I found up to now, which is a little nasty. Because uniqu_ptr expects a pointer I created int *fd to store the fd value, therefore, I had to close(*fd) and delete fd in my custom deleter.
(1) Is there a better way?
Options A and B, which are based on the hints provided by the mentioned web page, are much nicer but causing odd compiler errors.
(2) Does anyone know how to correctly use these alternatives?
I'm using Qt Creator 3.0.1 with CONFIG += c++11 option and gcc version 4.8.2
#include "ccommhandler.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <qdebug.h>
//for Option A and B
struct CloseHandleDeleter {
typedef int pointer;
void operator()(int handle) const
{
}
};
//custom deleter, working
class MyComplexDeleter
{
public:
MyComplexDeleter() {}
void operator()(int* ptr) const
{
qDebug() << "Deleting ";
close(*ptr);
delete ptr;
}
};
CCommHandler::CCommHandler()
{
//Option A doesn't work
//std::unique_ptr<int, CloseHandleDeleter> file( socket(AF_INET, SOCK_STREAM, 0) );
//Option B doesn't work
//std::unique_ptr<int, int()(int)> filePtr( socket(AF_INET, SOCK_STREAM, 0) , close);
MyComplexDeleter deleter;
int *fd = new int;
*fd = socket(AF_INET, SOCK_STREAM, 0);
std::unique_ptr<int, MyComplexDeleter> p( fd , deleter);
}
Edit:
The posted answer by Nevin is right, it solves my initial problem.
The comment of learnvst caused to rethink my problem, and I have to say I may made it much more complex than needed, because the following simple class should also solve my problem of auto-free the memory of a resource or as in my case, to close the file descriptor:
class SocketHandler
{
int _fd;
public:
SocketHandler(int FD):_fd(FD){}
~SocketHandler() { if(_fd!=-1) close(_fd); }
operator int() const { return _fd; }
};

Because fd isn't a pointer, I wouldn't try to pigeonhole it into unique_ptr. Instead, create a custom class whose interface is based on unique_ptr, as in (caution: totally untested):
class unique_fd
{
public:
constexpr unique_fd() noexcept = default;
explicit unique_fd(int fd) noexcept : fd_(fd) {}
unique_fd(unique_fd&& u) noexcept : fd_(u.fd_) { u.fd_ = -1; }
~unique_fd() { if (-1 != fd_) ::close(fd_); }
unique_fd& operator=(unique_fd&& u) noexcept { reset(u.release()); return *this; }
int get() const noexcept { return fd_; }
operator int() const noexcept { return fd_; }
int release() noexcept { int fd = fd_; fd_ = -1; return fd; }
void reset(int fd = -1) noexcept { unique_fd(fd).swap(*this); }
void swap(unique_fd& u) noexcept { std::swap(fd_, u.fd_); }
unique_fd(const unique_fd&) = delete;
unique_fd& operator=(const unique_fd&) = delete;
// in the global namespace to override ::close(int)
friend int close(unique_fd& u) noexcept { int closed = ::close(u.fd_); u.fd_ = -1; return closed; }
private:
int fd_ = -1;
};

Related

Arduino C++ classes needing each other

Here an example relating to my problem:
class classA
{
private:
int Value = 100;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
};
classA A = classA();
class classB
{
private:
int Value = 200;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
};
classB B = classB();
The problem is that class A can't access class B because it's definition is below it's own. My question is how can I define it so that class A has access to class B.
I tried to something like class classB; or class classB; classB B = classB; before classA begins.
Because I'm relatively new to programming I don't know how to solve such (probably easy) problems. Hope for some help!
This is a problem with circular dependencies. Luckily this one is pretty easy to fix: Just put the declaration and definition into separate files.
ClassA.h:
// Include guards to prevent double includes
#ifndef CLASS_A_H
#define CLASS_A_H
class classA
{
private:
int Value = 100;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_A_H
ClassB.h:
// Include guards to prevent double includes
#ifndef CLASS_B_H
#define CLASS_B_H
class classB
{
private:
int Value = 200;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_B_H
And now we need to actually define the functions, but in different files
ClassA.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classB B;
int classA::get_Value()
{
return Value;
}
void classA::set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
ClassB.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classA A;
int classB::get_Value()
{
return Value;
}
void classB::set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
Then, in your main file just include the two headers and you're good to go:
#include "A.h"
#include "B.h"
classB B = classB();
classA A = classA();
By the way, when you're on Arduino you can just create new .h and .cpp files and put them next to the .ino file and it should be found. You can even put them in folders, but then the include paths must be relative to each files, for example: #include "../include/file.h"

How to do non-blocking keyboard input on console app using Swift?

I want to make a simple console game using Swift 5. I need to read keyboard input without blocking the game animation (using emojis). The game keeps on going while there's no keyboard input, but will react accordingly if there are ones.
I've seen some example how to do it in other languages such as C and Python. I knew Swift has Darwin module that provide many POSIX functions. However, those C codes seem incompatible with Swift 5.
For example, how to convert the C code below into Swift? There's no FD_ZERO nor FD_SET in Darwin module.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>
struct termios orig_termios;
void reset_terminal_mode()
{
tcsetattr(0, TCSANOW, &orig_termios);
}
void set_conio_terminal_mode()
{
struct termios new_termios;
/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);
}
int kbhit()
{
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv);
}
int getch()
{
int r;
unsigned char c;
if ((r = read(0, &c, sizeof(c))) < 0) {
return r;
} else {
return c;
}
}
int main(int argc, char *argv[])
{
int key;
printf("press a key: ");
fflush(stdout);
set_conio_terminal_mode();
while (1) {
if (kbhit()) {
key = getch();
if (key == 13) {
printf("\n\r");
break;
} else if (key >= 20) {
printf("%c, ", key);
fflush(stdout);
}
}
else {
/* do some work */
printf(".");
usleep(10);
printf(".");
usleep(10);
printf(".");
usleep(10);
printf("\e[3D");
usleep(10);
}
}
reset_terminal_mode();
}
I expect swifty code to do the same thing in Swift.
The termios functions translate almost one-to-one to Swift:
#if os(Linux)
import Glibc
#else
import Darwin
#endif
var orig_termios = termios()
func reset_terminal_mode() {
tcsetattr(0, TCSANOW, &orig_termios)
}
func set_conio_terminal_mode() {
tcgetattr(0, &orig_termios)
var new_termios = orig_termios
atexit(reset_terminal_mode)
cfmakeraw(&new_termios)
tcsetattr(0, TCSANOW, &new_termios)
}
set_conio_terminal_mode()
The problem with select() is that FD_ZERO etc are “non-trivial” macros and not imported into Swift. But you can use poll() instead:
func kbhit() -> Bool {
var fds = [ pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0) ]
let res = poll(&fds, 1, 0)
return res > 0
}
An alternative is to use the Dispatch framework. Here is a simple example which might help you get started. A dispatch source is used to wait asynchronously for available input, which is then appended to an array, from where it is retrieved in the getch() function. A serial queue is used to synchronize access to the array.
import Dispatch
let stdinQueue = DispatchQueue(label: "my.serial.queue")
var inputCharacters: [CChar] = []
let stdinSource = DispatchSource.makeReadSource(fileDescriptor: STDIN_FILENO, queue: stdinQueue)
stdinSource.setEventHandler(handler: {
var c = CChar()
if read(STDIN_FILENO, &c, 1) == 1 {
inputCharacters.append(c)
}
})
stdinSource.resume()
// Return next input character, or `nil` if there is none.
func getch() -> CChar? {
return stdinQueue.sync {
inputCharacters.isEmpty ? nil : inputCharacters.remove(at: 0)
}
}

Robust type caster for STL-vector-like classes

I have a class that is quite similar to an STL-vector (the differences are not important for the pybind11 type caster, so I will ignore them here). I have written a type caster for this class. A minimal working example of my code is given below. An example showing the problem is included below the code.
The problem is that my caster is quite limited (because I have used py::array_t). In principle the interface does accept tuples, lists, and numpy-arrays. However, when I overload based on typename, the interface fails for inputted tuples and lists (simply the first overload is selected even though it is the incorrect type).
My question is: How can I make the type caster more robust? Is there an effective way to re-use as much as possible existing type casters for STL-vector-like classes?
C++ code (including pybind11 interface)
#include <iostream>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
// class definition
// ----------------
template<typename T>
class Vector
{
private:
std::vector<T> mData;
public:
Vector(){};
Vector(size_t N) { mData.resize(N); };
auto data () { return mData.data (); };
auto data () const { return mData.data (); };
auto begin() { return mData.begin(); };
auto begin() const { return mData.begin(); };
auto end () { return mData.end (); };
auto end () const { return mData.end (); };
size_t size () const { return mData.size (); };
std::vector<size_t> shape() const { return std::vector<size_t>(1, mData.size()); }
std::vector<size_t> strides() const { return std::vector<size_t>(1, sizeof(T) ); }
template<typename It> static Vector<T> Copy(It first, It last) {
Vector out(last-first);
std::copy(first, last, out.begin());
return out;
}
};
// C++ functions: overload based on type
// -------------------------------------
Vector<int> foo(const Vector<int> &A){ std::cout << "int" << std::endl; return A; }
Vector<double> foo(const Vector<double> &A){ std::cout << "double" << std::endl; return A; }
// pybind11 type caster
// --------------------
namespace pybind11 {
namespace detail {
template<typename T> struct type_caster<Vector<T>>
{
public:
PYBIND11_TYPE_CASTER(Vector<T>, _("Vector<T>"));
bool load(py::handle src, bool convert)
{
if ( !convert && !py::array_t<T>::check_(src) ) return false;
auto buf = py::array_t<T, py::array::c_style | py::array::forcecast>::ensure(src);
if ( !buf ) return false;
auto rank = buf.ndim();
if ( rank != 1 ) return false;
value = Vector<T>::Copy(buf.data(), buf.data()+buf.size());
return true;
}
static py::handle cast(const Vector<T>& src, py::return_value_policy policy, py::handle parent)
{
py::array a(std::move(src.shape()), std::move(src.strides()), src.data());
return a.release();
}
};
}} // namespace pybind11::detail
// Python interface
// ----------------
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("foo", py::overload_cast<const Vector<int > &>(&foo));
m.def("foo", py::overload_cast<const Vector<double> &>(&foo));
}
Example
import numpy as np
import example
print(example.foo((1,2,3)))
print(example.foo((1.5,2.5,3.5)))
print(example.foo(np.array([1,2,3])))
print(example.foo(np.array([1.5,2.5,3.5])))
Output:
int
[1 2 3]
int
[1 2 3]
int
[1 2 3]
double
[1.5 2.5 3.5]
A very easy solution is to specialise pybind11::detail::list_caster. The type caster now becomes as easy as
namespace pybind11 {
namespace detail {
template <typename Type> struct type_caster<Vector<Type>> : list_caster<Vector<Type>, Type> { };
}} // namespace pybind11::detail
Note that this does require Vector to have the methods:
clear()
push_back(const Type &value)
reserve(size_t n) (seems optional in testing)
Complete example
#include <iostream>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
// class definition
// ----------------
template<typename T>
class Vector
{
private:
std::vector<T> mData;
public:
Vector(){};
Vector(size_t N) { mData.resize(N); };
auto data () { return mData.data (); };
auto data () const { return mData.data (); };
auto begin() { return mData.begin(); };
auto begin() const { return mData.begin(); };
auto end () { return mData.end (); };
auto end () const { return mData.end (); };
size_t size () const { return mData.size (); };
void push_back(const T &value) { mData.push_back(value); }
void clear() { mData.clear(); }
void reserve(size_t n) { mData.reserve(n); }
std::vector<size_t> shape() const { return std::vector<size_t>(1, mData.size()); }
std::vector<size_t> strides() const { return std::vector<size_t>(1, sizeof(T) ); }
template<typename It> static Vector<T> Copy(It first, It last) {
printf("Vector<T>::Copy %s\n", __PRETTY_FUNCTION__);
Vector out(last-first);
std::copy(first, last, out.begin());
return out;
}
};
// C++ functions: overload based on type
// -------------------------------------
Vector<int> foo(const Vector<int> &A){ std::cout << "int" << std::endl; return A; }
Vector<double> foo(const Vector<double> &A){ std::cout << "double" << std::endl; return A; }
// pybind11 type caster
// --------------------
namespace pybind11 {
namespace detail {
template <typename Type> struct type_caster<Vector<Type>> : list_caster<Vector<Type>, Type> { };
}} // namespace pybind11::detail
// Python interface
// ----------------
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("foo", py::overload_cast<const Vector<double> &>(&foo));
m.def("foo", py::overload_cast<const Vector<int > &>(&foo));
}

std::sort using member function in the same class?

I have a class "PclProc" and I want to use std::sort.
I write a compare function in the same class because this comparing need the "in_ptr" which is a variable in the same class.
But as I did as following, there is always an error:
error: no matching function for call to
‘sort(std::vector::iterator, std::vector::iterator,
)’
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
bool PclProc::MyCompare(int id1, int id2)
{
return in_ptr->points[id1].z<in_ptr->points[id2].z;
}
float PclProc::MedianZDist(pcl::PointIndices cloud_indice)
{
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
int size=cloud_indice.indices.size();
float median_x,median_y;
...
Example of a functor being used for std::sort. vector D is the data, vector I is the indices to D. I is sorted according to D with std::sort using the functor. std::sort only creates one instance of class lessthan, then uses that one instance for all of the compares.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
typedef unsigned int uint32_t;
#define SIZE 16
class example{
public:
std::vector<uint32_t> D; // data
std::vector<uint32_t> I; // indices
example(void)
{
D.resize(SIZE);
I.resize(SIZE);
for(uint32_t i = 0; i < SIZE; i++){
D[i] = rand()%100;
I[i] = i;
}
}
void displaydata(void)
{
for(size_t i = 0; i < SIZE; i++)
std::cout << std::setw(3) << D[I[i]];
std::cout << std::endl;
}
class lessthan // lessthan functor for std::sort
{
public:
const example &x;
lessthan(const example &e ) : x(e) { }
bool operator()(const uint32_t & i0, const uint32_t & i1)
{
return x.D[i0] < x.D[i1];
}
};
void sortindices(void)
{
std::sort(I.begin(), I.end(), lessthan(*this));
}
};
int main()
{
example x;
x.displaydata();
x.sortindices();
x.displaydata();
return 0;
}

Compile error with boost bind in std::find_if

Consider this snippet:
#include <vector>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
template<typename PODType>
class SomeClass
{
public:
SomeClass() : m_pred(boost::bind(&SomeClass<PODType>::someMethodA, this, _1))
{
}
bool someMethodA(const PODType& elem)
{
return false;
}
bool someMethodB(const std::vector<PODType>& vec)
{
return (std::find_if(vec.begin(), vec.end(), m_pred(_1)) != vec.end());
}
private:
boost::function<bool(PODType)> m_pred;
};
int main(int argc, char* argv[])
{
SomeClass<int> obj;
std::vector<int> v;
obj.someMethodB(v);
return 0;
}
The compiler gives
error: no match for call to '(boost::function<bool(int)>) (boost::arg<1>&)'
note: no known conversion for argument 1 from 'boost::arg<1>' to 'int'
for the line return (std::find_if(vec.begin(), vec.end(), m_pred(_1)));
I'm trying to call someMethodA within the member predicate for the find_if calls.
Just pass m_pred, no need for m_pred(_1).