"Alex Vinokur" <al****@big-foot.com> wrote in message news:2u*************@uni-berlin.de...
[snip]
-----------------------
For not POD
Something like ?
-----------------------
[snip]
For POD
--------- C++ code : BEGIN ---------
#include <iostream>
#include <cassert>
using namespace std;
struct Foo
{
char ch1;
short sh;
char ch2;
char cstr[3];
char ch3;
};
char* get_as_cstr(const Foo& foo_i)
{
const int pure_size (sizeof(foo_i.ch1) + sizeof(foo_i.sh) + sizeof(foo_i.ch2) + strlen(foo_i.cstr) + sizeof(foo_i.ch3) + 1);
char* ret_ptr = new char [pure_size];
int i = 0;
ret_ptr[i++] = foo_i.ch1;
char* tmp_ptr = (char*)&foo_i.sh;
for (int j = 0; j < sizeof(foo_i.sh); j++) ret_ptr[i++] = *tmp_ptr++;
ret_ptr[i++] = foo_i.ch2;
for (int j = 0; j < strlen(foo_i.cstr); j++) ret_ptr[i++] = foo_i.cstr[j];
ret_ptr[i++] = foo_i.ch3;
ret_ptr[i] = 0;
assert (i < pure_size);
return ret_ptr;
}
#define SHOW(x,i) cout << #x << "[" << i << "] : ch = " << x[i] << "; hex = " << hex << uint (x[i]) << endl
int main ()
{
Foo foo;
foo.ch1 = 'a';
foo.sh = 0x6667;
foo.ch2 = 'b';
strcpy (foo.cstr, "de");
foo.ch3 = 'c';
char* charray1 = (char*)&foo;
char* charray2 = get_as_cstr (foo);
cout << "POD : Regular (char*)" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray1, i);
cout << endl;
cout << "POD : Function get_as_cstr" << endl;
for (int i = 0; i < sizeof (foo); i++) SHOW (charray2, i);
return 0;
}
--------- C++ code : END -----------
--------- Compilation & Run : BEGIN ---------
$ g++ -v
[omitted]
gcc version 3.3.3 (cygwin special)
$ g++ foo.cpp
// No errors/warnings
$ a
POD : Regular (char*)
charray1[0] : ch = a; hex = 61
charray1[1] : ch = ; hex = 3
charray1[2] : ch = g; hex = 67
charray1[3] : ch = f; hex = 66
charray1[4] : ch = b; hex = 62
charray1[5] : ch = d; hex = 64
charray1[6] : ch = e; hex = 65
charray1[7] : ch = ; hex = 0
charray1[8] : ch = c; hex = 63
charray1[9] : ch = ð; hex = fffffff0
POD : Function get_as_cstr
charray2[0] : ch = a; hex = 61
charray2[1] : ch = g; hex = 67
charray2[2] : ch = f; hex = 66
charray2[3] : ch = b; hex = 62
charray2[4] : ch = d; hex = 64
charray2[5] : ch = e; hex = 65
charray2[6] : ch = c; hex = 63
charray2[7] : ch = ; hex = 0
charray2[8] : ch = ; hex = 0
charray2[9] : ch = ; hex = 0
--------- Compilation & Run : END -----------
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html http://sourceforge.net/users/alexvn