将托管(C#)string []数组传递给COM DLL

时间:2009-05-17 22:46:04

标签: c# arrays com unmanaged managed

设定:
我有一个COM DLL,它调用托管C#DLL中的方法。此函数返回一个C#string []数组,该数组被封送到SAFEARRAY。

问题:
当我尝试访问safearray中的字符串时,我只获得字符串的第一个字符。我做错了什么?

代码:

    // Pointer to the managed interface
    DatabasePtr pODB(__uuidof(DBClass));

    // Get the string[] array from the managed method
    SAFEARRAY* safearray = pODB->GetStringArray();

    HRESULT hresult;

    long ubound;
    long lbound;

    hresult = SafeArrayGetUBound(safearray, 1, &ubound);
    hresult = SafeArrayGetLBound(safearray, 1, &lbound);

    long index;
    BSTR fromarray;

    for (; lbound <= ubound; lbound++)
    {
        index = lbound;

        hresult = SafeArrayGetElement(safearray, &index, (void*)&fromarray);

        char buffer[512];
        sprintf_s(buffer,"%s",fromarray);

        MessageBox(0, (LPCSTR)buffer, "...", 0);
    }

感谢您的帮助,
-Sean!

1 个答案:

答案 0 :(得分:2)

BSTR是一个unicode字符串,因此您必须使用wchar_t缓冲区和wsprintf_s。现在你打印第一个unicode字符的ANSI部分然后停在\ 0上。拜托,拜托,请不要堆叠溢出(原文!)。使用安全_vsnwprintf_s_l及其系列,您的代码是黑客的喜悦,因为它现在是你的,并且你会被计划。见http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx

相关问题