關於填充void*buf的一次小總結
要求是這樣的:
void *是某個函式的指標(fun(void * result)).
result的格式是這樣的,一個int值,若干個物件指標
假設是OBJ型別的物件
1,首先,我試了這種方法
OBJ * p = NULL;
memcpy(result,p)
這樣是出問題的。因為memcpy並不是將p的指標內容拷到result,而是將p指向的內容(也就是NULL)拷過去
這也說明我在程式設計的時候,有個問題,想當然的做事,不嚴謹。
2,然後我用了這種方法
(OBJ*)result = p
這種方法也是不對的,因為result是左值,不能被改變。
3。用了結構體方法
struct AAA
{
int x;
OBJ * p;
}A;
A a;
memcpy(result,&a,sizeof(a));
但是這樣,解決不了解析時候問題
4.最終用了這種方法
OBJ * p = NULL;
memcpy(result,&p)
然後在解析的時候,我發現了一個奇怪的現象
memcpy(&t,result,sizeof(int));
這樣,t能得到正確的值
cout<<(*((TT*)result)).s<<endl;
但是這樣,卻得不到正確的值
也就是說內建型別可以強轉指標,而類型別卻不可以。期待高手的回答
附上測試程式碼:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
using namespace std;
class TT
{
public:
int s;
};
int main()
{
TT t1;
TT t2;
t1.s = 1;
TT* p1 = &t1;
char *p = new char[100];
char * x = p ;
char * f = p;
int tint = 2;
memcpy(p,&tint,sizeof(tint));
p += sizeof(tint);
memcpy(p,&p1,sizeof(p1));
p += sizeof(p1);
memcpy(p,&tint,sizeof(tint));
int t;
memcpy(&t,x,sizeof(int));
cout<<*(int*)x<<endl;
// cout<<t<<endl;
x+=sizeof(int)/sizeof(char);
TT* ppT;
memcpy(&ppT,x,sizeof(TT*));
cout<<ppT->s<<endl;
x += sizeof(TT*);
cout<<*(int*)x<<endl;
//cout<<(*((TT*)x)).s<<endl;
delete []f;
return 0;
}