在CPP中创建和使用DLL

Creating and using a DLL in CPP

本文关键字:DLL 创建 CPP      更新时间:2023-10-16

我正在做一个项目,我正在创建一个小的DLL,然后还创建一个windows应用程序来使用它。

我不知道发生了什么事。

我在DLL中有一个名为"startPicadorVisual"的函数,它接受一个std::string参数。

在依赖于DLL的应用程序中,我在一个大多自动生成的。h文件中有以下代码:

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";
    }

在第二步调用GetProcAddress时失败。

在我的DLL中,函数定义如下:
void __declspec(dllexport) startPicadorVisual(string fixtureNamet);
PicadorResults __declspec(dllexport) getPicadorReading(string fixtureName);

谁能告诉我为什么这不起作用?

GetProcAddress失败,如果您给GetProcAddress的名称不匹配完全您正在调用的函数的名称。我所说的精确的是指所有的东西——组成函数名的字符,函数名必须匹配大小写,等等。

所以要么你的DLL导出了一个不同的名字而你没有意识到,要么你根本没有导出这个名字。

你可以很容易地找到导出的DLL函数的名字,你可以使用依赖程序在这里找到:http://www.dependencywalker.com/

同样,使用分配动态内存的c++对象(如std::string)作为参数也不是一个好主意。如果您这样做,您的DLL将只适用于

的应用程序
  1. 使用与DLL
  2. 相同版本的Visual c++编译。
  3. 在构建应用程序和DLL时使用相同的编译器选项
  4. 所有组件(DLL和app)必须使用C运行库的DLL版本。

否则,您的代码将有未定义的行为,很可能崩溃,即使您已经正确地检索了函数指针。