c++ - 在内存中分配多个结构

标签 c++ dll struct cen-xfs

我需要将多个值传递给内存,我需要为 CEN/XFS 创建不同的国家/地区。

此 API:CashDispenser - CDM

结构引用:WFSCDMCURRENCYEXP

我要怎么做:

HRESULT WINAPI WFPGetInfo(HSERVICE hService, DWORD dwCategory, LPVOID lpQueryDetails, DWORD dwTimeOut, HWND hWnd, REQUESTID ReqID) {
WFSRESULT * lpWFSResult;
WFSCDMSTATUS CdmStatus;
WFSCDMCAPS CdmCapabilities; 
WFSCDMCASHUNIT CdmCash;
WFSCDMCURRENCYEXP CdmCurrency;
HRESULT result;

result = WFMAllocateBuffer(sizeof(WFSRESULT), WFS_MEM_ZEROINIT | WFS_MEM_SHARE, (void**)&lpWFSResult); 

    if(result != WFS_SUCCESS){
        return WFS_ERR_INTERNAL_ERROR;
    }

if(dwCategory == WFS_INF_CDM_CURRENCY_EXP){

    const int countCurrencies = 2;

    WFSCDMCURRENCYEXP** ppCdmCurrencies;

    result = WFMAllocateMore(sizeof(WFSCDMCURRENCYEXP*) * (countCurrencies+1), lpWFSResult, (void**)&ppCdmCurrencies);

    lpWFSResult->hService=hService;      
    lpWFSResult->RequestID=ReqID;
    lpWFSResult->u.dwEventID=WFS_INF_CDM_CURRENCY_EXP;
    lpWFSResult->hResult=WFS_SUCCESS;

    result = WFMAllocateMore(sizeof(WFSCDMCURRENCYEXP), lpWFSResult, (void**)&ppCdmCurrencies[0]);

    WFSCDMCURRENCYEXP& cmdCurrency0(*ppCdmCurrencies[0]);
    memcpy(cmdCurrency0.cCurrencyID, "AED", 3);
    cmdCurrency0.sExponent = 0;

    WFSCDMCURRENCYEXP& cmdCurrency1(*ppCdmCurrencies[1]);
    memcpy(cmdCurrency1.cCurrencyID, "AFA", 3);
    cmdCurrency1.sExponent = 0;

    lpWFSResult->lpBuffer = ppCdmCurrencies;
    logFile.close();
}
}

最佳答案

你的代码看起来很 C-ish。

在 C++ 中执行此操作的惯用方法是:

struct WFSCDMCURRENCYEXP
{
   std::string     cCurrencyID;
   SHORT           sExponent;
};

std::vector<WFSCDMCURRENCYEXP> CdmCurrencies {
    { "ARG", 3 } ,
    { "EUA", 3 } ,
    // lots more countries
};

更新:

我刚刚注意到您显然与 c 风格的 API 交互,并且可能需要以其原始形式使用该 struct
尽管在 C++ 中,您仍然可以使用 std::vector 来管理该结构的动态分配的连续数组:

typedef struct _wfs_cdm_currency_exp
{
   CHAR            cCurrencyID[3];
   SHORT           sExponent;
} WFSCDMCURRENCYEXP, * LPWFSCDMCURRENCYEXP;

std::vector<WFSCDMCURRENCYEXP> CdmCurrencies {
    { { 'A', 'R', 'G' }, 3 } , // Note that the cCurrencyID is a non null terminated 
                               // array here
    { { 'E', 'U', 'A' }, 3 } ,
    // lots more countries
};

LPWFSCDMCURRENCYEXP pCdmCurrencies = &CdmCurrencies[0];

关于c++ - 在内存中分配多个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348631/

相关文章:

c++ - 如何用C++读取远程计算机上正在运行的进程列表

C# 泛型与 C++ 模板 - 需要澄清约束

C++: 'adding references' 到命名空间(和类库)?

c - 当您不知道要在字符串中放入多少个元素时,有没有办法在结构中初始化字符串数组?

c - 结构体内部的 union

c++ - 使用 C++ 在 ncurses 中打印子菜单的问题

c++ - 执行 cin 后计算标准输入中的字符数

windows - 在DllMain中,是否可以在没有DLL_THREAD_ATTACH的情况下发生DLL_THREAD_DETACH?

将 C dll 头文件转换为 Delphi Pascal 头文件

c - 为什么静态指针的初始化无效?