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

发布于 2024-07-20 00:46:40 字数 949 浏览 6 评论 0原文

设置:
我有一个 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);
    }

感谢您的帮助,
-肖恩!

Setup:
I have a COM DLL that calls a method inside a managed C# DLL. This function returns a C# string[] array, which is marshaled to a SAFEARRAY.

Problem:
When I try to access the strings within the safearray I only get the first char of the string. What am I doing wrong?

The code:

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

Thanks for your help,
-Sean!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩心不撩汉 2024-07-27 00:46:40

BSTR 是 unicode 字符串,因此您必须使用 wchar_t 缓冲区和 wsprintf_s。 现在你打印第一个 unicode 字符的 ANSI 部分,然后停在 \0 上。 拜托,拜托,不要像那样堆栈溢出(原文如此!)。 使用安全的 _vsnwprintf_s_l 及其系列,您的代码现在是黑客的最爱,您将被破解。 请参阅 http://msdn.microsoft.com/en-我们/库/d3xd30zz(VS.80).aspx

The BSTR is an unicode string, so you must use an wchar_t buffer and the wsprintf_s. Right now u print the ANSI part of the first unicode character then stop on the \0. And please, please, don't stack overflow like that (sic!). Use the safe _vsnwprintf_s_l and its family, your code is a hacker's delight as it is right now and u'll be pwned. See http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文