Home > database >  How to store text in wchar_t pointer parameter
How to store text in wchar_t pointer parameter

Time:06-24

I want to dll export some functions from cpp to dart and in order to do this I need to create a function with a pointer parameter where I will send text.

But after many searches I found no solution that works.

My question is: How to create a function with a wchar_t* parameter, and fill that variable with text? I have no knowledge of cpp pointers, I usually dont code in cpp.

Here is my code, it gives errors:


//extern "C" __declspec(dllexport) 
void getAudioDevices(wchar_t* output, int outSize)
{
    std::vector<DeviceProps> result = EnumAudioDevices(eRender);
    std::wstring listOutput(L"");
    if (!result.empty())
    {
        for (const auto& device : result)
        {
            std::wstring info(L"");
            info  = device.name; //PCWSTR
            info  = L"\n";
            info  = device.iconInfo; //PCWSTR
            info  = L"\n";
            info  = device.id; //LPWSTR
            info  = L"\n";
            info  = device.isActive ? L"true" : L"false";
            info  = L"\n[][][][]\n";
            listOutput  = info.c_str();
        }
    }
    wcscpy_s(output, outSize, listOutput.c_str());
}
int wmain(int argc, WCHAR* argv[])
{
    WCHAR output[1000];
    getAudioDevices(output, sizeof(output));
    cout << output << endl;

}

CodePudding user response:

sizeof(output) will return the number of bytes the array is. On Windows this will be 2000 instead of 1000 since each wchar_t is 2 bytes long.

But the the value passed to the wcscpy_s is the number of wide characters that your array can hold. Your array can hold 1000 wchar_t's. But your are actually telling wcscpy_s that it can hold more than that.

Change this:

getAudioDevices(output, sizeof(output));

To this:

getAudioDevices(output, sizeof(output)/sizeof(output[0]) );

Declare outSize to be of type size_t as well instead of int

  • Related