窗口下的 DLL



我需要从托管 c++ 代码动态加载.dll。下面的代码这样做

[DllImport("kernel32.dll", SetLastError = true,
        CharSet = CharSet::Unicode, ExactSpelling = true,
        CallingConvention = CallingConvention::StdCall)]
    static HMODULE LoadLibrary(LPCTSTR lpFileName);
    [DllImport("kernel32.dll", SetLastError = true,
        CharSet = CharSet::Unicode, ExactSpelling = true,
        CallingConvention = CallingConvention::StdCall)]
    static BOOL FreeLibrary(HMODULE hModule);
    [DllImport("kernel32.dll", SetLastError = true,
        CharSet = CharSet::Unicode, ExactSpelling = true,
        CallingConvention = CallingConvention::StdCall)]
    static FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName);
    typedef int (*CFunction)();
    int _tmain()
    {
        HMODULE pLib = LoadLibrary(TEXT("FunctionDLL.dll"));
        if(pLib != 0)
        {
            FARPROC function = GetProcAddress(pLib, "QFunction");
            if (function != 0)
                MessageBox::Show(Convert::ToString(function()));
            FreeLibrary(pLib);
        }
        else
        {
            MessageBox::Show(L"Error", L"Couldn't load ell");
            Close();
        }
        return 0;
    }

但函数始终为空。我认为这让我们错了。在 dll 代码下方:

.h 文件

#ifdef __FUNCTIONDLL__
#define __FUNCTIONDLL__
#ifdef FUNCTIONDLL_EXPORTS
    #define FUNCTIONDLL_API __declspec(dllexport)
#else
    #define FUNCTIONDLL_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
FUNCTIONDLL_API int QFunction();
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // __FUNCTIONDLL__

.cpp文件

#include "FunctionDLL.h"
int QFunction()
{
    return 42;
}

你的 C++ 项目中有 .def 吗? 如果不是,只需添加一个 .def

LIBRARY   FunctionDLL
EXPORTS
  QFunction   @1

相关内容

  • 没有找到相关文章

最新更新