|
| |
精品推荐 |
 |
|
| |
|
|
|
|
通过COM传送对象
|
日期:2007年5月3日 作者: 查看:[大字体
中字体 小字体]
|
首先我们来看一下服务器的GetArray方法。这个COM方法创建一个简单的对象,并将它送回给客户端。COM方法的本身挺简单,但它使用了一个颇复杂的称为CBlob的类。我将所有的串行化和安全数组代码放在CBlob类中。
file:// This method creates an object and sends it back to the client.
STDMETHODIMP CBlobData::GetArray(SAFEARRAY **pData)
{
// create object to send to server
CSimpleObj *pMyOb = new CSimpleObj();
// set the string data
pMyOb->SetString( "A SAFEARRAY from the server!" );
// create blob to serialize object
CBlob blob;
// load the object into the blob
*pData = blob.Load( pMyOb );
// delete the object
delete pMyOb;
return S_OK; }
GetArray方法首先创建一个CSimpleObject对象。然后将它传送给CBlob的Load()方法。Load方法将会串行化该对象,然后将它放进一个安全数组中。这个方法返回一个指向该安全数组的指针,此指针会被发送回客户端。该方法负责繁琐的串行化处理。
// Extract data from a CObject and use it to create a SAFEARRAY.
SAFEARRAY* CBlob::Load( CObject *pObj)
{
CMemFile memfile; // memory file
// define the flag which tells archive if it should load or store
long lMode = CArchive::store CArchive::bNoFlushOnDelete;
file:// create the archive using the memory file
CArchive ar(&memfile, lMode );
file:// m_pDocument is not used
ar.m_pDocument = NULL;
// serialize the object into the archive
ar.WriteObject(pObj);
// close the archive - the data is now stored in memfile
ar.Close();
// get the length (bytes) of the memory file
long llen = memfile.GetLength();
file:// detach the buffer and close the file
unsigned char *pMemData = memfile.Detach();
file:// set up safearray - SAFEARRAY is defined OAIDL.H
SAFEARRAY *psa;
// create a safe array to store the stream data
psa = SafeArrayCreateVector( VT_UI1, 0, llen );
// pointer to byte array
unsigned char *pData = NULL;
// get a pointer to the safe array. Locks the array.
SafeArrayAccessData( psa, (void**)&pData );
// copy the memory file into the safearray
memcpy( pData, pMemData, llen );
// clean up buffer
delete pMemData;
// unlock access to safearray
SafeArrayUnaccessData(psa);
// return a pointer to a SAFEARRAY allocated here
return psa;
}
以下就是Load方法所做的事情。你应该可以认出大部分的代码,因为我们已经讨论过它。
1、创建一个准备用作存储的archive
2、使用archive串行化该对象到一个CMemFile中
3、存储CMemFile缓冲的长度
4、将数据缓冲由CMemFile中脱离
5、创建SAFEARRAY
6、拷贝数据缓冲到SAFEARRAY
该存储文件缓冲被串行化填充。一旦填好,该缓冲就会从CMemFile对象脱离。CMemFile的Detach()方法必须被执行,以访问一个指针,该指针指向包含有串行化对象的内存缓冲。Detach还会令内存缓冲由CMemFile脱离,并且关闭该文件。
我们可以使用该指针做一个简单的内存复制,该操作将内存复制到SAFEARRAY的数据缓冲中。
// copy the memory file into the safearray
memcpy( pData, pMemData, llen );
该个步骤看来比想象中复杂。其实,这是由于memcpy()函数仅能复制连续的数据,因此我们不能将对象直接拷贝到安全数组中--这个对象在内存中的存储并不是连续的。CMemFile缓冲可确保是连续的,因此我们可以使用memcpy(),这样数据可通过COM被发送到客户端,并在那里被还原(反串行化)。
上一篇:理解软件保护技术之序列号方式
下一篇:网络游戏通讯模型初探
|
| 通过COM传送对象 相关文章: |
|
|
|
| 通过COM传送对象 相关软件: |
|
|
|
|