c# - 将字符串数组从 COM 传递到 C#

标签 c# c++ visual-c++ com-interop safearray

我需要通过类似 COM 的接口(interface)访问 COM dll 中的 C# 方法。其中一种方法需要将字符串数组作为输入传递。

正在创建一个 SAFEARRAY 并将其传递给 COM Interop。但是,这似乎不起作用,因为我在互操作层中看到了异常。 (System.Runtime.InteropServices.SafeArrayTypeMismatchException)。

显然,预期的类型似乎存在差异。

将代码粘贴到此处:

要调用的C#方法:

public long DoIt3(int nFiles, string[] fileNames);

调用相同内容的 C++ 代码:

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;
}

欢迎任何想法/建议。

最佳答案

我明白了!以下代码有效:

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;
}

感谢您的所有建议!

关于c# - 将字符串数组从 COM 传递到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085333/

相关文章:

c++ - char[] 上的一元运算符

c# - Collection<T> 与 List<T> 您应该在界面上使用什么?

c# - 将文件保存在音乐文件夹中 windows phone

c++ - 负 RGB 值

c++ - Access .ldb 文件和多重连接。

c++ - 更新到 Visual Studio 17.4.0 会产生与 TLS 相关的链接器错误

c++ - 在 visual studio 中 boost .ipp 文件支持

c# - 在 C# 中缓存异常实例是一种好习惯吗

c# - 十进制格式c#

c++ - 将文件中的十六进制数转换为 ASCII