Creating and using a DLL in CPP

2019-08-25 04:22发布

问题:

I am working on a project where I am creating a small DLL and then also creating a windows application to use it.

I can not figure out what is going on.

I have a function in the DLL called "startPicadorVisual" which takes one parameter which is a std::string.

In the application which is dependent on the DLL I have the following code in a mostly auto-generated .h file:

typedef void (__stdcall *f_startPicadorVisual)(string s);

namespace PicadorPrototype {
    f_startPicadorVisual startPicadorVisual;
    Form1(void) {
    //Load DLL Funcs
    HINSTANCE hGetProcIDDLL = LoadLibrary(L"..\\Debug\\Picador.dll");

    if (!hGetProcIDDLL) {
        std::cout << "could not load the dynamic library" << std::endl;
        throw "Bad Stuff";
    }

    startPicadorVisual = (f_startPicadorVisual)GetProcAddress(hGetProcIDDLL, "startPicadorVisual");

    if (!startPicadorVisual) {
        std::cout << "could not locate the function" << std::endl;
        throw "More Bad Stuff";
    }

When which fails on the second step when I call GetProcAddress.

The functions are defined as follows in my DLL:

void __declspec(dllexport) startPicadorVisual(string fixtureNamet);
PicadorResults __declspec(dllexport) getPicadorReading(string fixtureName);

Can anyone tell me why this isn't working?

回答1:

GetProcAddress fails if the name you give GetProcAddress doesn't match exactly the name of the function you're calling. By exact I mean everything -- characters that make up the function name, the function name must match casing, etc.

So either your DLL exported a different name and you didn't realize it, or you're not exporting the name at all.

The way you can find out the names of the exported DLL functions easily, you can use the Dependency Walker program found here: http://www.dependencywalker.com/

Also, it isn't a good idea to use C++ objects that allocate dynamic memory such as std::string as parameters. If you do that, your DLL will only work for applications that

  1. Are compiled with the same version of Visual C++ as the DLL
  2. Use the same compiler options when building the application and DLL
  3. All components (DLL and app) must use the DLL version of the C runtime library.

Otherwise, your code would have undefined behavior, more than likely crash, even if you got as far as retrieving the function pointer correctly.



标签: c++ dll