【发布时间】:2021-04-09 08:53:27
【问题描述】:
这是我的 test.cpp 文件。(我也使用 makefile 来创建 dll 文件)
//#include <iostream>
int foo(int a)
{
if (a > 1)
return a + 1;
else
return a + 2;
}
当我在 python 中运行以下代码时
import os
import ctypes
lib_bfs = ctypes.WinDLL("D:\\advanced_programming\\HW7\\cpp_part\\libtest.dll")
print(lib_bfs)
一切正常,我从 python 得到这个输出。
<CDLL 'D:\advanced_programming\HW7\cpp_part\libtest.dll', handle 69d00000 at 0x2b7677e6400>
但是当我以这种方式更改我的 test.cpp 时(我只是取消注释 iostream):
#include <iostream>
int foo(int a)
{
if (a > 1)
return a + 1;
else
return a + 2;
}
我从 python 收到以下错误。
Traceback (most recent call last):
File "d:/advanced_programming/HW7/cpp_part/connector.py", line 4, in <module>
lib_bfs = ctypes.WinDLL("D:\\advanced_programming\\HW7\\cpp_part\\libtest.dll")
File "c:\users\ali\appdata\local\programs\python\python38\lib\ctypes\__init__.py", line 373, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'D:\advanced_programming\HW7\cpp_part\libtest.dll' (or one of its dependencies). Try using the full path with constructor syntax.
这也是我的依赖 enter image description here
顺便提一下,当我使用 Linux 时,一切都很好。(我只是使用 .so 文件)但是 windows 可能会出现一些问题
感谢您的帮助。
【问题讨论】:
-
如果你需要导出一个类或者一个sruct,你需要像
class __declspec(dllexport) Color这样指定__declspec(dllexport)。成员函数不需要显式地一一导出,导出类会自动导出所有成员。 -
@dhirajWishal tnx。你能给我一个很好的文档来阅读它吗?
-
官方 MSVC 文档将是一个很好的起点:docs.microsoft.com/en-us/cpp/cpp/…
-
@DhirajWishal 我认为他不想导出类(它可能只是一个内部类),只导出函数(使用 C 链接)。似乎问题出现了,因为使用
std::string引入了对libstdc++.dll(或其他东西)的依赖,而这在加载他的libbfs.dll期间未找到。 -
@heapunderrun 哦,是的,可能就是这样。我的坏:/