2009-05-17 107 views
0

设置:
我有一个COM DLL调用托管的C#DLL中的方法。该函数返回一个C#string []数组,该数组被封送到SAFEARRAY。传递托管(C#)字符串[]数组到一个COM DLL

问题:
当我尝试到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!

回答

2

BSTR是一个Unicode字符串,因此您必须使用wchar_t缓冲区和wsprintf_s。现在你打印第一个Unicode字符的ANSI部分,然后停在\ 0上。请,请不要像这样溢出(原文如此!)。使用安全的_vsnwprintf_s_l及其家族,你的代码是一种黑客的喜悦,因为它现在就会被使用。见http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx

+0

感谢您的帮助。你是什​​么意思,“不要像这样堆栈溢出?” – Sean 2009-05-18 00:45:46

相关问题