帮助复制内存 [英] help on copying memory
问题描述
我对C ++还是很陌生,谁能帮助我解决内存复制问题(目标的无效指针):
切出的代码如下所示:
I am quite new to C++, could anyone help me to fix memory copy issue (invalid pointer of destination):
cut out code looks like this:
int cWrapper::EncryptRun(const unsigned char *data, NewCamDData *cd, int len, bool UseMsgId, comm_type_t commType)
{
memcpy(desKey , cd->desKey, 16);
int sz = sizeof(DES_key_schedule);
memcpy(&ks1, &cd->ks1, sz);
memcpy(&ks2, &cd->ks2, sz);
unsigned char netbuf[CWS_NETMSGSIZE];
memset(&netbuf[2],0,cdLen+2);
memcpy(&netbuf[cdLen+4],data,len);
netbuf[cdLen+4+1]=(data[1]&0xf0)|(((len-3)>>8)&0x0f);
netbuf[cdLen+4+2]=(len-3)&0xff;
//...assign values
//this is where the problem is for the data pointer
memcpy(&data,&netbuf,len);
}
数据指向一个240字节的数组,而netbuf是要复制到数据的新字节数组.
为了完成通话,我添加了调用该通话的方法:
data points to an array of 240 bytes, and netbuf is new byte array to be copied to data.
To complete calls, I am adding the method which calls this:
DllExport int CALLBACK EncryptA(NewCamDData *cd, unsigned char *pBuffer, int len, bool UseMsgId, comm_type_t commType)
{
//cw assigned in class initialisation:
cw = new cWrapper(525);
int ret = cw->EncryptRun(pBuffer, cd, len, UseMsgId, commType);
return ret; //*pBuffer;
}
从VB.NET调用此方法.
调试向我显示了此信息:
This method called from VB.NET.
debugging shows me this:
?netbuf
0x0038ebec ""
[0]: 0 <-first byte of array
[1]: 48 '0'
[2]: 169 '©'
?data
0x0280aee4 "€ ¤+ØÔ&§HœõRøî°¶l-áþ«…"
?sizeof(data)
4
?*data
128 '€' <-first byte of array
推荐答案
使用
memcpy(data, netbuf, len);
因为data
和netbuf
已经是指针.
但是,这将产生编译器错误,因为目标data
被声明为const
.由于不使用cd
的事实,我认为
because data
and netbuf
are already pointers.
However, this will produce a compiler error, because the destination data
is declared as const
. Due to the fact that cd
is not used, I assume that
memcpy(cd, netbuf, len)
是你想要的.
为确保不会发生缓冲区溢出,您还可以添加一些检查:
is what you want.
To be sure that no buffer overflows occur, you may also add some checks:
ASSERT(cdLen + 4 + len <= CWS_NETMSGSIZE);
ASSERT(cdLen + 7 <= CWS_NETMSGSIZE);
// This only when copying to cd
ASSERT(len <= sizeof(NewCamDData));
memcpy(data,netbuf,len);
我认为,这就是您应该打电话的方式.要这样调用,数据参数声明应为"unsigned char * data",不应为常量指针!.
还要确保-
i think, this is how you should call. To call like this the data parameter declaration should be "unsigned char *data" should not be a constant pointer!.
Also make sure -
CWS_NETMSGSIZE>=len.
这篇关于帮助复制内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!