Serialize and deserialize objects in C ++ - mysql

I'm new to C ++, I can not find a detailed example of how to serialize an object in binary so I can save it to the mysql server and then be deserialized.
The object looks like this:
class house{
public:
int houseNumber;
bool isEmpty;
Dweller *dweller;
};
class Dweller{
public:
int phoneNumber;
bool man;
Backpack backpack;
};
class Backpack{
public:
int item1;
int item2;
int item3;
int item4;
float weight;
bool empty;
};
I have to serialize the house object, which owns the other objects.

I was able to solve the problem using:
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
See I used #include "boost/serialization/vector.hpp" because now the 'dweller' are in a vector to make things easier
Then the code stayed like this:
class house{
public:
int houseNumber;
bool isEmpty;
std::vector<Dweller> dweller;
private:
friend class boost::serialization::access;
template <class archive>
void serialize(archive &ar, const unsigned int version)
{
ar &houseNumber;
ar &isEmpty;
ar &dweller;
}
};
class Dweller{
public:
int phoneNumber;
bool man;
Backpack backpack;
private:
friend class boost::serialization::access;
template <class archive>
void serialize(archive &ar, const unsigned int version)
{
ar &phoneNumber;
ar &man;
ar &backpack;
}
};
class Backpack{
public:
int item1;
int item2;
int item3;
int item4;
float weight;
bool empty;
private:
friend class boost::serialization::access;
template <class archive>
void serialize(archive &ar, const unsigned int version)
{
ar &item1;
ar &item2;
ar &item3;
ar &item4;
ar &weight;
ar ∅
}
};
So to serialize I used:
#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <sstream>
int main()
{
Backpack _backpack;
_backpack.item1 = 0;
_backpack.item1 = 1;
_backpack.item1 = 2;
_backpack.item1 = 3;
_backpack.item1 = 4;
_backpack.weight = 3.21;
_backpack.empty = false;
Dweller _dweller1;
_dweller.phoneNumber = 1234567;
_dweller.man = false;
_dweller.backpack = _backpack;
Dweller _dweller2;
_dweller.phoneNumber = 7654321;
_dweller.man = true;
_dweller.backpack = _backpack;
std::vector<Dweller> _dwellers;
_dwellers.push_back(_dweller1);
_dwellers.push_back(_dweller2);
house _house;
_house.houseNumber = 4;
_house.isEmpty = false;
_house.dweller = _dwellers;
/*Serializing*/
std::stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa << _house;
/*Deserializing*/
boost::archive::binary_iarchive ia(ss);
house _house2;
ia >> _house2;
}

Related

RISC-V fuzzing emulation

I am new to this but I need to emulate RISC-V using qemu. As a start for my fuzzing project, how can I do give qemu an instruction set and get the changes in the registries as an output.
I probably understand your question. Because I don't have a riscv-related environment here, I can only provide a solution.
For example, in riscv, we design a function to get the values of all registers, relying on qemu's plugin module (such as qemu_plugin_register_vcpu_insn_exec_cb()).
plugin_test.c
#include <inttypes.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <glib.h>
#include <qemu-plugin.h>
QEMU_PLUGIN_EXPORT int qemu_plugin_version = QEMU_PLUGIN_VERSION;
#define CPU_SIZE 32
static int cpu_num;
static int cpu_value[CPU_SIZE]={0};
static void vcpu_insn_exec_before(unsigned int cpu_index, void *)
{
for (size_t i = 0; i < cpu_num; i++)
{
/* code */
for (size_t j = 0; j < CPU_SIZE; i++)
{
if(cpu_value[j] != get_cpu_register(i,j)) {
// The value of cpu has changed
...
} else {
// The value of cpu has not changed
...
}
}
}
}
static void vcpu_tb_trans(qemu_plugin_id_t id, struct qemu_plugin_tb *tb)
{
size_t n = qemu_plugin_tb_n_insns(tb);
size_t i;
for (i = 0; i < n; i++) {
struct qemu_plugin_insn *insn = qemu_plugin_tb_get_insn(tb, i);
qemu_plugin_register_vcpu_insn_exec_cb(
insn, vcpu_insn_exec_before, QEMU_PLUGIN_CB_NO_REGS,void *);
}
}
static void plugin_exit(qemu_plugin_id_t id, void *p)
{
}
QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
const qemu_info_t *info,
int argc, char **argv)
{
if(info->system_emulation) {
cpu_num = info->system.smp_vcpus;
} else {
cpu_num = 1;
}
qemu_plugin_register_vcpu_tb_trans_cb(id, vcpu_tb_trans);
qemu_plugin_register_atexit_cb(id, plugin_exit, NULL);
return 0;
}
api-ext.c
void *qemu_get_cpu(int index);
static uint32_t get_cpu_register(unsigned int cpu_index, unsigned int reg) {
uint8_t* cpu = qemu_get_cpu(cpu_index);
return *(uint32_t*)(cpu + 33488 + 5424 + reg * 4);
}
It should be noted that the content in api-ext.c is obtained from others. This is the function used to obtain the value of arm cpu. You need to check the source code or documentation for riscv.

Use member function as template argument to create a static wrapper

I'm trying to write a c++11 wrapper around a C API, and basically there is a way to register notifications with a static function pointer, which also passes me back an "opaque" pointer, which are provided at a later point, basically a pointer to classes I create, in this example the class foo. Basically, I'm trying to create a static function `helper<..>::call that has the API's signature, but generates code to call my member function on the instance that the c++ wrapper created, and is passed in through an "opaque" pointer along with it. This static function then also converts the arguments when finally calling the member function.
I seem to have this almost working, but I'm having trouble creating a "nicer" public function register_handler in this example, which hides the "uglier" internals. This is the error I'm getting:
test.cpp:154:37: error: no matching function for call to ‘register_handler<&foo::bar>(const char [6])’
154 | register_handler<&foo::bar>("test2"); // <-- trying to wrap it into a function so I can use only one template argument
| ^
test.cpp:137:6: note: candidate: ‘template<class T, class R, class ... Args, R (T::* Func)(Args ...)> void register_handler(const char*)’
137 | void register_handler(const char* name)
| ^~~~~~~~~~~~~~~~
This is my test code:
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <cassert>
// inspired by https://stackoverflow.com/a/7943765/2129246
template <typename T>
struct func_traits:
public func_traits<decltype(&T::operator())>
{
};
template <typename R, typename... Args>
struct func_traits<R(*)(Args...)>
{
enum { arity = sizeof...(Args) };
typedef R result_type;
using all_args = std::tuple<Args...>;
template <size_t i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};
template <typename C, typename R, typename... Args>
struct func_traits<R(C::*)(Args...) const>
{
enum { arity = sizeof...(Args) };
typedef C class_type;
typedef R result_type;
using all_args = std::tuple<Args...>;
template <size_t i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};
template< std::size_t... Ns >
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
struct value
{
std::string str_;
template <typename T>
value(T val):
str_(std::to_string(val))
{
}
value(const char* str):
str_(str)
{
}
value(const std::string& str):
str_(str)
{
}
operator int() const
{
return std::stoi(str_);
}
operator double() const
{
return std::stof(str_);
}
operator std::string() const
{
return str_;
}
};
std::map<std::string, void(*)(void*, const std::vector<value>&)> g_handlers;
template <typename T, T>
struct helper;
template <typename T, typename R, typename... Args, R(T::*Func)(Args...)>
struct helper<R(T::*)(Args...), Func>
{
template <size_t... Is>
static void expand(T* obj, const std::vector<value>& args, indices<Is...>)
{
assert(sizeof...(Is) <= args.size());
(obj->*Func)((args[Is])...);
}
static void call(void *p, const std::vector<value>& args)
{
T* obj = reinterpret_cast<T*>(p);
expand(obj, args, typename make_indices<sizeof...(Args)>::type());
}
static void reg_handler(const char* name)
{
g_handlers.insert(std::make_pair(name, call));
};
};
template <typename Obj>
void call_handler(Obj& obj, const char* name, const std::vector<value>& args)
{
auto it = g_handlers.find(name);
if (it != g_handlers.end())
it->second(reinterpret_cast<void*>(&obj), args);
else
std::cout << "handler not registered: " << name << std::endl;
}
// The code below somehow doesn't ever match this template
template <typename T, typename R, typename... Args, R(T::*Func)(Args...)>
void register_handler(const char* name)
{
helper<R(T::*)(Args...), Func>::reg_handler(name);
}
struct foo
{
void bar(int v, const std::string& str, double f)
{
std::cout << "bar: v=" << v << " str=" << str << " f=" << f << std::endl;
};
};
int main()
{
// register member function handlers before we have any instances
helper<decltype(&foo::bar), &foo::bar>::reg_handler("test"); // <-- works, but "ugly" and exposes internal implementation
register_handler<&foo::bar>("test2"); // <-- trying to wrap it into a function so I can use only one template argument
// now we have an instance
foo f;
// call the previously registered handler
call_handler(f, "test", {1, "2", 3.45});
call_handler(f, "test2", {1, "2", 3.45});
return 0;
}
The simple answer for C++11 is: You can't!
From C++17 you are able to use auto also for non type template parameters as a function pointer or member function pointer is not a type here and you have no syntax to describe your function pointer type.
In C++17 you can use it like this:
struct foo
{
void bar(){}
};
template <typename T, T>
struct helper;
template <typename T, typename R, typename... Args, R(T::*Func)(Args...)>
struct helper<R(T::*)(Args...), Func>
{
static void reg_handler(const char* name)
{
// ... here your code continues
}
};
template < auto T >
struct X
{
};
template <typename T, typename R, typename... Args, R(T::*Func)(Args...)>
struct X<Func>
{
static void register_handler( const char* name )
{
helper<R(T::*)(Args...), Func>::reg_handler(name);
}
};
int main()
{
X<&foo::bar>::register_handler("check");
}

C++/CLI classes and IList

I'm trying to deserialize the following JSON using C++/CLI
[
{
"id":"046e075ad92684",
"NfcA":{
"maxTransceiveLength":253,
"sak":0,
"atqa":"4400",
"timeout":618
},
"Ndef":[
{
"records":[
{
"id":"",
"tnf":1,
"type":"54",
"payload":"02656e48656c6c6f206d792041737365742049442069733a20303030303031"
}
]
}
],
"tech":[
"android.nfc.tech.NfcA",
"android.nfc.tech.MifareUltralight",
"android.nfc.tech.Ndef"
],
"time":1472468356002
}
]
I have already declared the following classes in order to get the contents of JSON data.
ref class tech {
public: String^ tech1;
public: String^ tech2;
public: String^ tech3;
};
ref class Record {
public: String^ id;
public: int tnf;
public: String^ type;
public: String^ payload;
};
ref class Topic_nfc {
public: String^ id;
public: ref class NfcA {
public: int maxTransceiveLength;
public: int sak;
public: int atqa;
public: int timeout;
};
public: ref class Ndef {
public: System::Collections::Generic::IList<Record^>^ records;
};
public: System::Collections::Generic::IList<Ndef^>^ Ndef;
public: System::Collections::Generic::IList<String^>^ tech;
public: unsigned long long time;
public:
NfcA^ NfcA;
};
After deserialization I can access id and maxTransceiveLength normally using
printf("MyRawdata[i]->id : %s\n", MyRawdata[i]->id);
printf("MyRawdata[i]->NfcA->maxTransceiveLength : %d\n", MyRawdata[i]->NfcA->maxTransceiveLength);
where MyRawdata derived from
System::Collections::Generic::IList<Topic_nfc^>^ MyRawdata = JsonConvert::DeserializeObject<System::Collections::Generic::IList<Topic_nfc^>^>(MyJson);
However, I can not figure out how we can access Ndef and tech data members such as payload. Can you indicate which is the equivelant for IList ?
Thank you
Thanks to #Lucas Trzesniewski help, I concluded that these lists can be accessed using the following code.
for (int k = 0 ; k < MyRawdata[i]->Ndef->Count ; k++) {
printf("MyRawdata[i]->Ndef[k]->records[k]->payload : %s\n", MyRawdata[i]->Ndef[k]->records[k]->payload);
}
for (int k = 0 ; k < MyRawdata[i]->tech->Count ; k++) {
printf("MyRawdata[i]->tech[k] : %s\n", MyRawdata[i]->tech[k]);
}
Actually, it was a matter of syntax to access the data in the respective classes.

Passing Host Function as a function pointer in __global__ OR __device__ function in CUDA

I am currently developing a GPU version of a CPU function
(e.g. function Calc(int a, int b, double* c, souble* d, CalcInvFunction GetInv )), in which a host function is passes as a function pointer(e.g. in above example GetInv is the host function of CalcInvFunction type). My question is, if i have to put Calc() function entirely in GPU, i have to pass the GetInv function as a function pointer argument in device function/kernel function, and is that possible?
Yes, for a GPU implementation of Calc, you should pass the GetInv as a __device__ function pointer.
It is possible, here are some worked examples:
Ex. 1
Ex. 2
Ex. 3
Most of the above examples demonstrate bringing the device function pointer all the way back to the host code. This may not be necessary for your particular case. But it should be fairly obvious from above how to grab a __device__ function pointer (in device code) and use it in a kernel.
Finally, i have been able to pass a host function as a function pointer in cuda kernel function (__global__ function). Thanks to Robert Crovella and njuffa for the answer. I have been able to pass a class member function(cpu function) as a function pointer to a cuda kernel. But, the main problem is, i can only pass the static class member function. I am not being able to pass the function not declared as static.
For Example:
/**/
__host__ __device__
static int
CellfunPtr(
void*ptr, int a
);
/**/
The above function work because this member function is declared as static member function. If i do not declare this member function as a static member as ,
/**/
__host__ __device__
int
CellfunPtr(
void*ptr, int a
);
/**/
then it doesnt work.
The complete code has four files.
First file
/*start of fundef.h file*/
typedef int (*pFunc_t)(void* ptr, int N);
/*end of fundef.h file*/
Second file
/*start of solver.h file*/
class CalcVars {
int eqnCount;
int numCell;
int numTri;
int numTet;
public:
double* cellVel;
double* cellPre;
/** Constructor */
CalcVars(
const int eqnCount_,
const int numCell_,
const int numTri_,
const int numTet_
);
/** Destructor */
~CalcVars(void);
public:
void
CalcAdv();
__host__ __device__
static int
CellfunPtr(
void*ptr, int a
);
};
/*end of solver.h file*/
Third file
/*start of solver.cu file*/
#include "solver.h"
__device__ pFunc_t pF1_d = CalcVars::CellfunPtr;
pFunc_t pF1_h ;
__global__ void kernel(int*a, pFunc_t func, void* thisPtr_){
int tid = threadIdx.x;
a[tid] = (*func)(thisPtr_, a[tid]);
};
/* Constructor */
CalcVars::CalcVars(
const int eqnCount_,
const int numCell_,
const int numTri_,
const int numTet_
)
{
this->eqnCount = eqnCount_;
this->numCell = numCell_;
this->numTri = numTri_;
this->cellVel = (double*) calloc((size_t) eqnCount, sizeof(double));
this->cellPre = (double*) calloc((size_t) eqnCount, sizeof(double));
}
/* Destructor */
CalcVars::~CalcVars(void)
{
free(this->cellVel);
free(this->cellPre);
}
void
CalcVars::CalcAdv(
){
/*int b1 = 0;
b1 = CellfunPtr(this, 1);*/
int Num = 50;
int *a1, *a1_dev;
a1 = (int *)malloc(Num*sizeof(int));
cudaMalloc((void**)&a1_dev, Num*sizeof(int));
for(int i = 0; i <Num; i++){
a1[i] = i;
}
cudaMemcpy(a1_dev, a1, Num*sizeof(int), cudaMemcpyHostToDevice);
//copy addresses of device functions to host
cudaMemcpyFromSymbol(&pF1_h, pF1_d, sizeof(pFunc_t));
kernel<<<1,42>>>(a1_dev, pF1_h, this);
cudaDeviceSynchronize();
cudaMemcpy(a1, a1_dev, Num*sizeof(int), cudaMemcpyDeviceToHost);
};
int
CalcVars::CellfunPtr(
void* ptr, int a
){
//CalcVars* ClsPtr = (CalcVars*)ptr;
printf("Printing from CPU function\n");
//int eqn_size = ClsPtr->eqnCount;
//printf("The number is %d",eqn_size);
return a-1;
};
/*end of solver.cu file*/
Fourth file
/*start of main.cpp file*/
#include "solver.h"
int main(){
int n_Eqn, n_cell, n_tri, n_tetra;
n_Eqn = 100;
n_cell = 200;
n_tri = 300;
n_tetra = 400;
CalcVars* calcvars;
calcvars = new CalcVars(n_Eqn, n_cell, n_tri, n_tetra );
calcvars->CalcAdv();
system("pause");
}
/*end of main.cpp file*/

Calling a Base Class Construtor in a function of Derived Class

I am trying to call a constructor of a Base Class in a function of Derived Class. Here is the code:
Classes:
#pragma once
#include "CAR_TYRE_DOOR.h"
#include <string>
using namespace std;
//#ifndef 1_A_H_B
//#define 1_A_H_B
class Honda_Civic: public Car
{
private:
string CNG_y_n;
public:
Honda_Civic();
Honda_Civic(string CNG);
Honda_Civic(Honda_Civic& H1);
void set_CNG_y_n(string S);
string get_CNG_y_n();
void print();
};
class BMW: public Car
{
private:
string conv_y_n;
public:
BMW();
BMW(string S);
BMW(BMW& BMW1);
void set_conv_y_n(string S);
string get_conv_y_n();
void print();
};
class Mercedes: public Car
{
private:
int no_WS;
string SGR_y_n;
public:
Mercedes();
Mercedes(int no_WS, string SGR_y_n);
Mercedes(Mercedes& Merc);
//::Car( Merc1);
void set_no_WS(int n);
void set_SGR(string SGR);
int get_no_WS();
string get_SGR();
void print();
};
//#endif
The BaseClass functions:
//#include "BMW+MERC.h"
#include "CAR_TYRE_DOOR.h"
#include "Honda.h"
#include "S_R.h"
#include <iostream>
#include <string>
using namespace std;
void Car::set_color(string S)
{
S = this->color;
}
void Car::set_model(string S)
{
S = this->model;
}
void Car::set_cost(float x)
{
x = this->cost;
}
string Car::get_color()
{
return this->color;
}
string Car::get_model()
{
return this->model;
}
float Car::get_cost()
{
return this->cost;
}
Car::Car()
{
}
Car::Car(string color, string model, float cost)
{
this->color = "white";
this->model = "2011";
this->cost = 1000000;
}
Car::Car(Car& C1)
{
this->color = C1.color;
this->model = C1.model;
this->cost = C1.cost;
for(int i=0; i<4; i++)
{
DX[i] = C1.DX[i];
}
for(int i=0; i<4; i++)
{
TX[i] = C1.TX[i];
}
}
void Car::print_car()
{
cout <<"Car color: "<<get_color()<<endl;
cout <<"Car model: "<<get_model()<<endl;
cout <<"Car door color: "<<DX[0].get_color()<<endl;
cout <<"Car door vendor: "<<DX[0].get_vendor()<<endl;
cout <<"Tyre vendor: "<<TX[0].get_vendor()<<endl;
for(int i=0; i<4; i++)
{
cout <<"Tyre"<< i+1 <<"type: "<<TX[i].get_rubber_type()<<endl;
}
}
The Derived Class:
#include "Honda.h"
#include <iostream>
#include <string>
using namespace std;
Mercedes::Mercedes()
{
}
Mercedes::Mercedes(int no_WS, string SGR_y_n)
{
this->no_WS = 4;
this->SGR_y_n = "Yes";
}
Mercedes::Mercedes(Mercedes& Merc)
{
Mercedes::Car( Merc);
this->no_WS = Merc.no_WS;
this->SGR_y_n = Merc.SGR_y_n;
}
void Mercedes::set_no_WS(int n)
{
this->no_WS = n;
}
void Mercedes::set_SGR(string SGR)
{
this->SGR_y_n = SGR;
}
int Mercedes::get_no_WS()
{
return this->no_WS;
}
string Mercedes::get_SGR()
{
return this->SGR_y_n;
}
void Mercedes::print()
{
Mercedes.print_car();
cout <<"Number of Woofer Speakers: "<<get_no_WS()<<endl;
cout <<"Sunglass Roof: "<<get_SGR()<<endl;
}
Now in the copy constructor of the derivedclass, i am trying to call the copy constructor of the base class using:
Mercedes::Mercedes(Mercedes& Merc)
{
Mercedes::Car( Merc);
this->no_WS = Merc.no_WS;
this->SGR_y_n = Merc.SGR_y_n;
}
See this: Mercedes::Car( Merc);
to implement this, please tell me the syntax.
The proper way to call constructor hierarchies is like this:
class Car
{
public:
Car () { }
Car (cosnt Car &) {}
};
class Mercedes : public Car
{
public:
Mercedes () { }
Mercedes (const Mercedes &) {}
};
Mercedes :: Mercedes () : Car() { }
Mercedes :: Mercedes (const Mercedes &car) : Car(car) { }
A copy constructor looks like this (notice the const):
Class :: Class (const Class &)