Il passaggio di un array gestito (C #) string [] per una DLL COM
Domanda
Impostazione:
Ho un DLL COM che chiama un metodo all'interno di un C # DLL gestita. Questa funzione restituisce un array di C # string [], che è il marshalling per un SAFEARRAY.
Problema:
Quando provo ad accedere alle stringhe all'interno della matrice protetta ho solo il primo carattere della stringa. Che cosa sto facendo di sbagliato?
Il codice:
// 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);
}
Grazie per il vostro aiuto,
-Sean!
Soluzione
Il BSTR è una stringa unicode, quindi è necessario utilizzare un buffer wchar_t
e il wsprintf_s
. In questo momento u stampare la parte ANSI del primo carattere unicode poi fermarsi sul \ 0. E per favore, per favore, non impilare di overflow del genere (sic!). Utilizzare il _vsnwprintf_s_l
sicuro e la sua famiglia, il codice è la delizia di un hacker come è adesso e u'll essere pwned. Vedere http://msdn.microsoft.com/en- us / library / d3xd30zz (VS.80) aspx