Search code examples
c++windowsdlldynamic-linkinghandle

Calling fuctions from the .dll library using dynamic linking


Ok, so I', writting a C++ code for the MCP2221 converter. In order to use it I try to implement the .dll file. Namely mcp2221_dll_m_dotnetv4_x86.dll which can be downloaded from: https://www.microchip.com/DevelopmentTools/ProductDetails/PartNo/ADM00559

I've tried to implement it but I still cannot call the functions and I cannot find the reason why.

I use the following code:

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string.h>

using namespace std;
typedef string(WINAPI *MYPROC)();

int main()
{
    HINSTANCE hinstLib; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.
    char a;

    hinstLib = LoadLibrary(TEXT("mcp2221_dll_m_dotnetv4_x86.dll"));

    // If the handle is valid, try to get the function address.

    if (hinstLib != NULL)
    {
        cout << "LIB\tloaded" << endl;

        MYPROC ProcAdd = (MYPROC)GetProcAddress(hinstLib, "M_Mcp2221_GetLibraryVersion");

        // If the function address is valid, call the function.

        if (NULL != ProcAdd)
        {
            cout << "FUNC\tloaded" << endl;
            string s= ProcAdd();
            fRunTimeLinkSuccess = TRUE;
        }
        else
        {
            cout << "FUNC\tNOT loaded" << endl;
        }
        // Free the DLL module.

        fFreeResult = FreeLibrary(hinstLib);
    }
    else
    {
        cout << "LIB\tNOT loaded" << endl;
    }
    return 0;
}

The function is defined in the specification in the following way:

String^ M_Mcp2221_GetLibraryVersion()

Description: Returns the version number of the DLL Returns: String containing the library version Use Marshal.GetLastWin32Error() to determine the error code if the function fails.

I still get the LIB loaded FUNC NOT loaded output.

Could anyone tell me what I keep doing wrong? Will appreciate a lot.


Solution

  • Probably, you are using wrong dll and wrong function name.

    You are trying to load function from dll for .Net-managed code - MCP2221_DLL(v2.2.1)\managed\MCP2221DLL-M-dotNet4\x86\mcp2221_dll_m_dotnetv4_x86.dll. With an utility that shows functions exported from dll, I haven't found any functions that are exported from this one.

    Try using unmanaged dll MCP2221_DLL(v2.2.1)\unmanaged\dll\mcp2221_dll_um_x86.dll. It has function _Mcp2221_GetLibraryVersion@4