C ++: casting to void * and vice versa

* --- Change - now the whole source *

When I debug it at the end, "get" and "value" have different meanings! Perhaps I will convert to void * and return to the User incorrectly?

#include <db_cxx.h>
#include <stdio.h>

struct User{
User(){}
int name;
int town;
User(int a){};
inline int get_index(int a){
    return town;
} //for another stuff
};
int main(){ 
try {
DbEnv* env = new DbEnv(NULL);
env->open("./", 
    DB_CREATE | DB_INIT_MPOOL | DB_THREAD | 
DB_INIT_LOCK | DB_INIT_TXN | DB_RECOVER | DB_INIT_LOG, 0);
Db* datab = new Db(env, 0);
datab->open(NULL, "db.dbf", NULL, DB_BTREE, DB_CREATE | DB_AUTO_COMMIT, 0);

Dbt key, value, get;
char a[10] = "bbaaccd";
User u;
u.name = 1;
u.town = 34;
key.set_data(a);
key.set_size(strlen(a) + 1 );
value.set_data((void*)&u);
value.set_size(sizeof(u));
get.set_flags(DB_DBT_MALLOC);

DbTxn* txn;
env->txn_begin(NULL, &txn, 0);
datab->put(txn, &key, &value, 0);
datab->get(txn, &key, &get, 0);
txn->commit(0);
User g;
g = *((User*)&get);
printf("%d", g.town);
getchar();
return 0;
}catch (DbException &e){
    printf("%s", e.what());
    getchar();
}

Decision

create a kind of "serializer" to convert all PODs to void *, and then combine these fragments

PS Or I would rewrite the user in the POD type, and everything will be fine, I hope.

Add

This is strange, but ... I throw a defenetly non-pod object into void * and vice versa (it has std :: string inside), and everything is fine (without sending it to db and vice versa). How could this happen? And after I said and sent the 'trough' db defenetly pod object (no additional methods, all pod members, this is a simple structure {int a; int b; ...}). What is wrong with my approach?

'

... , , , ! !.. !... AAh!.. Lord... ( 99,999 - "", ... ...) - ? ?

+3
4

User POD, undefined ++.

Edit:

db_cxx.h, get_doff(), get_dlen() get_data() - Dbt , ( ) ?

+7

put(), , . :

+1

​​ "" . , , . , Dbt. , , :

datab->get(txn, &key, &get, 0);
void* data = get.get_data();
User g = *((User*)data);

Dbt, , , .

+1

- :

User               user;
std::stringstream  dbStotrStream;

dbStoreStream << user;  // Serialize user
std::string        dbStore(bdStoreStream.str());
value.set_data(dbStore.c_str());  
value.set_size(dbStore.lenght());

////  Put in DB

:

//// Get from DB

std::string        dbStore(get.get_data(),get.get_date() + get.get_size());
std::stringstream  dbStoreStream(dbStore);
User              outUser;

 dbStoreStream >> outUSer;
0

Source: https://habr.com/ru/post/1729268/


All Articles