0

我需要从托管的 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 我们错了。下面是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;
}
4

1 回答 1

0

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

LIBRARY   FunctionDLL
EXPORTS
  QFunction   @1
于 2012-11-24T20:01:59.477 回答