我需要通过类似COM的接口访问COM dll中的C#方法。其中一个方法需要将一个字符串数组作为输入传递。
创建SAFEARRAY并将其传递给COM Interop。但是,这似乎没有用,因为我在互操作层中看到了一个例外。 (System.Runtime.InteropServices.SafeArrayTypeMismatchException)。
显然,预计类型似乎存在差异。
在此处粘贴代码:
public long DoIt3(int nFiles, string[] fileNames);
int _tmain()
{
TCHAR *fileNames[128] = { TEXT("C:\\Program Files\\IBM\\RTC.NET"),
TEXT("C:\\KIRAN\\Work\\RFT"), TEXT(".\\bin\\Debug") };
SAFEARRAY *pSA = CreateSafeStringArray(3, fileNames);
_tprintf(TEXT("%d"), pIManaged->DoIt3(3, pSA));
SafeArrayDestroy(pSA);
}
static SAFEARRAY *CreateSafeStringArray(long nElements, TCHAR *elements[])
{
SAFEARRAYBOUND saBound[1];
saBound[0].cElements = nElements;
saBound[0].lLbound = 0;
SAFEARRAY *pSA = SafeArrayCreate(VT_VARIANT, 1, saBound);
if (pSA == NULL)
{
return NULL;
}
for (int ix = 0; ix < nElements; ix++)
{
VARIANT v;
VariantInit(&v);
v.vt = VT_BSTR;
v.bstrVal = elements[ix];
long rgIndicies[1];
rgIndicies[0] = ix + saBound[0].lLbound;
HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, &v);
_tprintf(TEXT("%d"), hr);
VariantClear(&v);
}
return pSA;
}
欢迎任何想法/建议。
答案 0 :(得分:1)
对于BSTR字符串数组,您可以直接在数组上设置BSTR值,还可以you need to allocate memory for your BSTR elements,您可以使用ATL / MFC CString:
...
psa = SafeArrayCreate( VT_BSTR, 1, saBound);
HRESULT hr = SafeArrayLock( psa );
//TODO: test for hr success
if (pSA == NULL)
{
return NULL;
}
for (int ix = 0; ix < nElements; ix++)
{
long rgIndicies[1];
rgIndicies[0] = ix + saBound[0].lLbound;
CString tempstr(elements[ix]);
((BSTR*)psa->pvData)[ix] = tempstr.AllocSysString();
_tprintf(TEXT("%d"), hr);
}
hr = SafeArrayUnlock( psa );
//TODO: test for hr success
...
答案 1 :(得分:1)
我明白了!以下代码有效:
static SAFEARRAY *CreateSafeStringArray(long nElements, TCHAR *elements[])
{
SAFEARRAYBOUND saBound[1];
saBound[0].cElements = nElements;
saBound[0].lLbound = 0;
SAFEARRAY *pSA = SafeArrayCreate(VT_BSTR, 1, saBound);
if (pSA == NULL)
{
return NULL;
}
for (int ix = 0; ix < nElements; ix++)
{
BSTR pData = SysAllocString(elements[ix]);
long rgIndicies[1];
rgIndicies[0] = saBound[0].lLbound + ix;
HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, pData);
_tprintf(TEXT("%d"), hr);
}
return pSA;
}
感谢你的所有建议!