How to call "StrCpyW" function from "shlwapi.dll"? in C++?

85 views Asked by At

I use Code::Blocks as IDE.

And I should use "libshlwapi.a" library in order to use "StrCpyW" function.

But I want to use that function without the library.

In order to achieve that, I should call "shlwapi.dll".

So, I write my codes like this:

void StrCpyW(PWSTR a_wcResultString, PCWSTR p_cwcSourceString)
{
    typedef PWSTR (*tdStrCpyW)(PWSTR, PCWSTR);

    HMODULE hmShlwapi;

    hmShlwapi = LoadLibraryW(L"shlwapi.dll");

    if(hmShlwapi)
    {
        tdStrCpyW fnStrCpyW = (tdStrCpyW)GetProcAddress(hmShlwapi, "StrCpyW");

        fnStrCpyW(a_wcResultString, p_cwcSourceString);
    }

    FreeLibrary(hmShlwapi);
}

So, what is wrong in my codes?

2

There are 2 answers

1
Aykhan Hagverdili On BEST ANSWER

Just use wcscpy instead so you don't have to load any libraries.

0
Remy Lebeau On

Your tdStrCpyW type is missing the WINAPI (__stdcall) calling convention:

typedef PWSTR (WINAPI *tdStrCpyW)(PWSTR, PCWSTR);
               ^^^^^^

Most Win32 APIs on Windows use __stdcall. Only a handful of functions, mainly those that have C-style variadic parameters, such as wsprintf(A/W), use __cdecl instead. This detail tends to be omitted in MSDN documentation.

Also, you are not checking if GetProcAddress() fails. And your call to FreeLibrary() is in the wrong place if LoadLibraryW() fails.

Try this:

void StrCpyW(PWSTR a_wcResultString, PCWSTR p_cwcSourceString)
{
    typedef PWSTR (WINAPI *tdStrCpyW)(PWSTR, PCWSTR);

    HMODULE hmShlwapi = LoadLibraryW(L"shlwapi.dll");
    if (hmShlwapi)
    {
        tdStrCpyW fnStrCpyW = (tdStrCpyW) GetProcAddress(hmShlwapi, "StrCpyW");
        if (fnStrCpyW)
            fnStrCpyW(a_wcResultString, p_cwcSourceString);

        FreeLibrary(hmShlwapi);
    }
}