You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ DLL返回BSTR至Excel VBA无显示问题排查求助

问题:Excel调用C++ DLL反转字符串返回空值

我在C++库中编写了一个函数,用于接收Excel指定单元格中的字符串并反转后返回,采用了BSTR与std::string互转的方法。但在Excel中调用该DLL函数时出现异常:函数未正确返回Excel可识别显示的BSTR。当单元格输入“test”并调用reverse_word函数时,预期返回“tset”,实际却仅返回空字符串。

C++ DLL头文件

#pragma once

#ifdef EXCELMATHLIB_EXPORTS
#define EXCELMATHLIB_API __declspec(dllexport)
#else
#define EXCELMATHLIB_API __declspec(dllimport)
#endif

extern "C" EXCELMATHLIB_API BSTR reverse_word(BSTR excelW);

C++ DLL实现代码

BSTR WINAPI reverse_word(BSTR excelW)
{
    std::string str = ConvertBSTRToMBS(excelW);
    reverse(str.begin(), str.end());
    return ConvertMBSToBSTR(str);
}

std::string ConvertBSTRToMBS(BSTR bstr)
{
    int wslen = ::SysStringLen(bstr);
    return ConvertWCSToMBS((wchar_t*)bstr, wslen);
}

std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen)
{
    int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);

    std::string dblstr(len, '\0');
    len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
        pstr, wslen /* not necessary NULL-terminated */,
        &dblstr[0], len,
        NULL, NULL /* no default char */);

    return dblstr;
}

BSTR ConvertMBSToBSTR(const std::string& str) 
{
    int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
        str.data(), str.length(),
        NULL, 0);

    BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
    ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
        str.data(), str.length(),
        wsdata, wslen);
    return wsdata;
}

Excel VBA模块代码

Private Declare PtrSafe Function reverse_word_cpp _
    Lib "C:\Users\artil\source\repos\ExcelMathLib\x64\Debug\ExcelMathLib.dll" Alias "reverse_word" _
    (ByRef str As String) As String

Function reverse_word(word As String) 'reverse word wrapper function
    Dim result As String
    result = reverse_word_cpp(word)
    MsgBox result
    reverse_word = StrConv(result, vbFromUnicode)
End Function

测试情况

  • 从单元格调用包装函数(如=reverse_word(A1),A1内容为“test”),MsgBox和单元格均显示空内容。
  • 单独测试ConvertMBSToBSTR函数正常:在C++中直接返回ConvertMBSToBSTR("test")时,Excel通过StrConv(..., vbFromUnicode)可正确显示结果。推测问题出在reverse_word函数的处理流程中。

内容的提问来源于stack exchange,提问作者azncookiethief

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:57:34