【问题标题】:Having trouble importing function from C++ dll error LNK 2019从 C++ dll 错误 LNK 2019 导入函数时遇到问题
【发布时间】:2013-06-25 02:57:49
【问题描述】:

我正在尝试用 C++ 编写和测试一个 dll 文件,只要我想要文件系统级别的访问权限,我就可以调用它。尝试在 C++ 中访问此 dll 中的方法时,我目前非常头疼。奇怪的是,我能够在单独的 C# 程序中轻松调用代码,但我想了解 dll 交互在 C++ 中是如何工作的。

这是我的虚拟可执行文件的 .cpp,它应该只调用我的“newMain”测试方法。

// dummy.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
//#pragma comment(lib,"visa32.lib")
#pragma message("automatic link to adsInterface.dll")
#pragma message(lib, "adsInterface.lib"

extern "C" int __stdcall newMain();

int _tmain(int argc, _TCHAR* argv[])
{
 newMain();
 std::string i;
 std::cin >> i
 return 0;
}

问题是,当我运行它时,我得到了这个错误:

error LNK2019: unresolved external symbol _newMain@0 referenced in function _wmain
error LNK1120: 1 unresolved externals

这是 adsInterface 的 .h:

// adsInterface.h

#ifndef ADSINTERFACE_H
#define ADSINTERFACE_H

/* //save this for later i have no clue how this really works.
#ifdef ADSAPI_EXPORTS
#define ADSAPI __declspec(dllexport)
#else
#define ADSAPI __declspec(dllexport)
#endif
*/

namespace ADSInterface
{
  //test method. should print to console.
  __declspec(dllexport) int __stdcall newMain();

  void hello();
}
#endif

这是我的 adsInterface .cpp:

// adsInterface.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "adsInterface.h"
#include <iostream>

namespace ADSInterface
{
  /* this is where the actual internal class and other methods will go */

  void hello()
  {
    std::cout << "hello from the DLL!" << std::endl;
  }


  __declspec(dllexport) int __stdcall newMain()
  {
    hello();
    return 0;
  }
}

我还将包含我在编译 dll 时使用的 .def 文件:

; adsInterface.def - defines exports for adsInterface.dll

LIBRARY ADSINTERFACE
;DESCRIPTION 'A C++ dll that allows viewing/editing of alternate data streams'

EXPORTS
  newMain @1

奇怪的是,我可以用这一行在 C# 中导入方法(我也不必包含 .lib 文件):

[DllImport("./adsInterface.dll")] private static extern void newMain();

当我正常调用它时它运行:

newMain();

我已经阅读了许多关于如何导入 dll 函数的不同指南,并且我已经达到了我认为我只是将不同语言之间的不同导入方式组合在一起并且只是把事情弄得一团糟的地步。如果有人能够提供一些关于我应该如何在 C++ 中导入 dll 方法的见解,将不胜感激。

【问题讨论】:

    标签: c++ dll import declspec


    【解决方案1】:

    删除此声明:

    extern "C" int __stdcall newMain();
    

    并从 _tmain 调用 ADSInterface::newMain()。

    在发布的代码中,您没有定义与该声明匹配的任何内容,是吗?

    或者让实现调用另一个,或者将一个从命名空间拖到全局。

    【讨论】:

    • #include "adsInterface.h" in dummy.cpp
    • 效果很好,感谢所有帮助。我正在为此撕毁我的头发。只是一个小问题,有没有办法让我不必包含标题?像这样我只需要将 dll 作为资源提供?
    • 您可以使用正确的声明,因为它当前位于标题中 - 在命名空间内。你不会有整个麻烦是首先避免命名空间:)。
    • 那么,如果我要删除命名空间并让 newMain() 是全局的,我不需要标题吗?还是标题仍然是必要的?
    • “标题”没有真正的特殊性,它的内容只是粘贴在#include 处。声明行是直接在 .cpp 文本中还是来自 .h 没有区别。所以标题永远不是“必要的”,只是为了避免重复。
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2020-02-19
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多