LNK2019构造函数/析构函数使用 C++ Dll



我正在开发一个带有C包装器的C++DLL,以便在Python和C#中使用它。所以我在Visual Studio上创建了一个项目(DLL)来开发和编译它。这里没问题。我甚至可以在Python上使用我的DLL而不会遇到麻烦。

但是,在视觉上,我想在与 DLL 相同的解决方案中创建另一个项目来测试 DLL。

所以我创建了第二个项目(Win32 Windows 应用程序),将 .h添加到头文件中,添加了指向我在测试项目文件夹中添加的.lib文件的链接,但是当我尝试编译它时,我遇到了关于LNK2019的错误,从构造函数开始:

error LNK2019: unresolved external symbol "public: __cdecl Projet::Projet(void)" (??Projet@@QEAA@XZ) referenced in function main

DLL = Projet/测试 = Projet_Test

普罗杰·

#pragma once
#include "Projet_inc.h"
class Projet
{
public:
Projet();
~Projet();
int multiply(int arg1, int arg2);
int result;
};

Projet_inc.h

#ifdef PROJET_EXPORTS
#  define EXPORT __declspec(dllexport)
#else
#  define EXPORT __declspec(dllimport)
#endif
#define CALLCONV_API __stdcall
#ifdef __cplusplus
extern "C" // C wrapper
{
#endif
typedef struct Projet Projet; // make the class opaque to the wrapper
EXPORT Projet* CALLCONV_API cCreateObject(void);
EXPORT int CALLCONV_API cMultiply(Projet* pDLLobject, int arg1, int arg2);
#ifdef __cplusplus
}
#endif

普罗杰特.cpp

#include "stdafx.h"
#include "Projet.h"
Projet::Projet() {}
Projet::~Projet() {}
int Projet::multiply(int arg1, int arg2) {
result = arg1 * arg2;
return result;
}
Projet* EXPORT CALLCONV_API  cCreateObject(void)
{
return new Projet();
}
int EXPORT CALLCONV_API  cMultiply(Projet* pDLLtest, int arg1, int arg2)
{
if (!pDLLtest)
return 0;
return pDLLtest->multiply(arg1, arg2);
}

Projet_Test.cpp

// Projet_Test.cpp : définit le point d'entrée pour l'application console.
//
#include "stdafx.h"
#include "Projet.h"
int main()
{
Projet object;
return 0;
}

在视觉对象上,我选择测试项目作为启动项目以获取信息。我在SO上看了很多帖子,但目前没有找到解决方案。提前谢谢你。

您需要__declspec(dllexport)所有要直接调用的函数,而不仅仅是 C 函数。

在您的示例中,您应该能够正确调用 C 包装器函数cCreateObjectcMultiply,因为它们已正确导出,但您将无法调用底层C++函数,如Projet::Projet()Projet::~Projet()

有两种方法可以解决此问题:您可以将这些函数更改为内联函数,并将其实现移动到标头。这样,客户端项目将不再为这些函数调用 DLL 中的代码,而只是直接编译内联定义本身。一般来说,这显然不是一个明智的方法。或者,用__declspec(dllexport)标记C++成员函数,就像使用 C 函数一样。

请注意,Visual Studio 倾向于在版本之间中断C++ ABI,因此您需要确保用于编译 dll 的编译器版本与用于编译客户端应用程序的编译器版本兼容。如果两个部分都使用相同的Visual Studio版本编译,或者如果您坚持使用普通的C接口,则这不是问题。

首先,关于缺少符号 EpsCndCoreDll 的错误在这里似乎脱离了上下文,您应该收到有关将结构重新定义为类(类 Projet)的编译错误。

可能您需要使用类似的东西:

class Projet;
typedef Projet* PProjet;

并进一步使用 PProject 作为不透明句柄。

您还需要导出 Projet 类,如下所示:

class EXPORT Projet

以便能够通过客户端实例化该类或添加返回引用的工厂函数。

确保已将 DLL 引用添加到 DLL。

最新更新