使用COM提供SafeArray数据

    在前一篇博文《读取SafeArray数据》我们介绍了C#读取安全数组;那么我们的COM怎么编写呢?

   1. 定义SAFEARRAY变量

SAFEARRAY *pSArray = NULL;


   2. 释放此变量

SafeArrayDestroy(pSArray);


   3. 建立向量表

pSArray = SafeArrayCreateVector(VT_UI1, 0, 32);

           向量变量( VT_UI1)的定义: MSDN

VT_EMPTY

Variable type is not specified.

VT_NULL

Variable type is NULL.

VT_I2

Variable type is 2-byte signed INT.

VT_I4

Variable type is 4-byte signed INT.

VT_R4

Variable type is 4-byte real.

VT_R8

Variable type is 8-byte real.

VT_CY

Variable type is currency.

VT_DATE

Variable type is date.

VT_BSTR

Variable type is binary string.

VT_DISPATCH

Variable type is IDispatch FAR*.

VT_ERROR

Variable type is SCODE.

VT_BOOL

Variable type is Boolean; True=-1, False=0.

VT_VARIANT

Variable type is VARIANT FAR*.

VT_UNKNOWN

Variable type is IUnknown FAR*.

VT_UI1

Variable type is unsigned char.

VT_RESERVED

This element is reserved.

VT_BYREF

Variable type is a pointer to data.

VT_ARRAY

Variable type is a safe array.


   4. 写入数据

SafeArrayPutElement(pSArray, &l, &inqReport[l]);



      实例程序(COM方法):

      AA:屏蔽的数值

STDMETHODIMP CRepoFmt::getInqRepo(ULONG iStation, SAFEARRAY** ret)
{
	SAFEARRAY *pSArray = NULL;

	unsigned char inqReport[32];
	unsigned char xorByte = AA;
	int iStationID = 0;

	if (iStation < 1) 
		iStationID = 1;
	else
		iStationID = iStation;

	inqReport[0]  = AA;
	inqReport[1]  = AA;
	inqReport[2]  = AA;
	inqReport[3]  = AA;
	inqReport[4]  = (iStationID % AA);
	inqReport[5]  = (iStationID / AA);
	inqReport[6]  = AA;
	inqReport[7]  = AA;
	inqReport[8]  = AA;
	inqReport[9]  = AA;
	inqReport[10] = AA;
	inqReport[11] = AA;
	
	for (int i = 1; i < 18; i++)
		xorByte ^= inqReport[i];

	inqReport[18] = xorByte;

	// Fill the inqReport etc.
	for (int j = 12; j < 18; j++)
		inqReport[j] = 0;
	for (int k = 19; k < 32; k++)
		inqReport[k] = 0;

	if (!ret)
		return E_POINTER;

	if (*ret) {
		SafeArrayDestroy(pSArray);
		*ret = NULL;
	}

	pSArray = SafeArrayCreateVector(VT_UI1, 0, 32);
	for (long l = 0; l < 32; l++)
		SafeArrayPutElement(pSArray, &l, &inqReport[l]);

	*ret = pSArray;

	return S_OK;
}



你可能感兴趣的:(使用COM提供SafeArray数据)