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

C++中适配MT4 JournalRequest时JSON转LPCSTR仅返回首字符求助

问题原因与解决方法

你的问题核心是宽字符串转窄字符串时的类型不匹配:

  • filter是utility::string_t(本质是std::wstring,宽字符串,每个字符占2字节)
  • LPCSTR是const char*(窄字符串指针,每个字符占1字节)

直接将宽字符串指针传入JournalRequest时,宽字符串的第一个字符高字节为0,会被C风格字符串判定为结束符,因此只返回第一个字符。


修复代码

替换你代码中字符串转换和函数调用的部分,用Windows APIWideCharToMultiByte完成正确的宽→窄字符串转换:

int total;
ServerLog* records;
web::json::value jTrades;
utility::string_t from, to, filter, mode;

std::wistringstream ss;
web::json::value jRecords;
time_t _from = 0, _to = 0;
int _mode;
int k = 0;
int year = 0, month = 0, day = 0, hour = 0, min = 0;

mode = params[U("mode")];
to = params[U("to")];
from = params[U("from")];
filter = params[U("filter")];

// 新增:正确转换宽字符串为窄字符串
std::string narrow_filter;
// 先获取转换所需缓冲区大小
int buffer_len = WideCharToMultiByte(CP_UTF8, 0, filter.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (buffer_len > 0) {
    narrow_filter.resize(buffer_len);
    // 执行转换
    WideCharToMultiByte(CP_UTF8, 0, filter.c_str(), -1, &narrow_filter[0], buffer_len, nullptr, nullptr);
}

loginfo << "Input From: " << _from << " To:" << _to << " Filter:"  << filter << endl;

// 调用函数时传入转换后的窄字符串指针
records = man->JournalRequest(_mode, (__time32_t)_from, (__time32_t)_to, narrow_filter.c_str(), &total);

关键说明

  1. 编码选择:示例中用CP_UTF8作为编码,若MT4的JournalRequest要求系统默认编码,可替换为CP_ACP。
  2. 缓冲区安全:先调用一次WideCharToMultiByte获取所需长度,再分配空间,避免溢出。
  3. 额外提醒:你的代码中_mode、_from、_to变量未赋值,后续需要补充逻辑处理这些参数,否则会导致未定义行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:33:57