C++ equivalent of PHP's pack()
My question is simple.
Is there an equivalent of PHP's pack()
and unpack()
function in the C++开发者_如何转开发 STL?
If no, is there an alternative to achieve the same goal?
https://www.php.net/pack
Thanks.
If your goal is serializing data, you can use Google protocol buffers to achieve it.
http://code.google.com/apis/protocolbuffers/
A while back I wrote a small a library in C that does this functionality. I placed my code on Google code here: code.google.com/p/packlib/
There is no serialization mechanism in the STL. Depending on what you want to do you could either use a library such as the one in Boost or you could write your own serialization code, which can be a viable alternative especially if your data is rather simple.
Structs are very much like the unpack function within PHP.
These pieces of code, are basically equivalent.
PHP:
define('ISP_TINY', 4);
class IS_TINY
{
const PACK = 'CCCC';
const UNPACK = 'CSize/CType/CReqI/CSubT';
public $Size = 4;
public $Type = ISP_TINY;
public $ReqI;
public $SubT;
public function __construct($rawPacket)
{
$pkClass = unpack($this::UNPACK, $rawPacket);
foreach ($this as $property => $value)
{
$this->$property = $pkClass[$property];
}
}
}
C++:
#define ISP_TINY = 4;
struct IS_TINY // General purpose 4 byte packet
{
byte Size; // Always 4
byte Type; // Always ISP_TINY
byte ReqI;
byte SubT;
};
A while ago I needed the same functionality so I wrote a single-header library for this. It supports most of the functionality from php's pack() / unpack()
. The library is available on github here.
精彩评论