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

问题描述 投票:0回答:3

我正在使用C包装器开发C ++ DLL,以便在Python和C#中使用它。所以我在Visual Studio上创建了一个项目(DLL)来开发和编译它。这里没问题。我甚至可以毫无困难地在Python上使用我的DLL。

但是,在Visual上,我想在与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 = Project / Test = Project_Test

Projet.h

#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

Projet.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;
}

在Visual上,我选择测试项目作为启动项目以获取信息。我在SO上看了很多帖子,但我现在还没有找到解决方案。先感谢您。

c++ c windows dll wrapper
3个回答
1
投票

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

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

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

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


1
投票

首先,关于缺失符号EpsCndCoreDll的错误似乎在这里脱离了上下文,你应该得到关于将struct重新定义为类(类Projet)的编译错误。

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

class Projet;
typedef Projet* PProjet;

并使用PProject作为不透明的句柄。

您还需要导出Project类,如:

class EXPORT Projet

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


-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.