【问题标题】:Passing a managed (C#) string[] array to a COM DLL将托管 (C#) 字符串 [] 数组传递给 COM DLL
【发布时间】:2009-05-17 22:46:03
【问题描述】:

设置:
我有一个 COM DLL,它调用托管 C# DLL 中的方法。此函数返回一个 C# string[] 数组,该数组被封送为 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);
    }

感谢您的帮助,
-肖恩!

【问题讨论】:

    标签: c# arrays com unmanaged managed


    【解决方案1】:

    BSTR 是一个 unicode 字符串,因此您必须使用 wchar_t 缓冲区和 wsprintf_s。现在你打印第一个 unicode 字符的 ANSI 部分,然后在 \0 上停止。请,请不要像那样堆叠溢出(原文如此!)。使用保险箱_vsnwprintf_s_l 及其系列,您的代码就像现在一样是黑客的乐趣,您将被破解。见http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx

    【讨论】:

    • 感谢您的帮助。 “不要那样堆栈溢出”是什么意思?
    • sprintf 如果 fromarray 大于 512 会溢出缓冲区
    • 好的。它不会大于 512,但无论如何我都会走安全路线。再次感谢。
    • 另外,你没有提到我应该使用 MessageBoxW,而不是 MessageBox...
    • 对,您的数据库例程也可以访问。您可能希望使用通用 TCHAR 类型并将项目设置更改为 Unicode。或者,如果您必须坚持使用 ANSI,请先通过 MultiByteToWideChar (msdn.microsoft.com/en-us/library/dd319072(VS.85).aspx) 之类的方式将接收到的 fromarray 转换为 ANSI。您还应该查看 BSTR 包装器帮助程序 _bstr_t 和 CComBSTR。我更喜欢 _bstr_t 见msdn.microsoft.com/en-us/library/zthfhkd6(VS.80).aspx
    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2010-12-18
    • 2020-09-11
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多