Skip to main content
 首页 » 编程设计

python之一个简单的 python 程序无法访问我的 dll

2025年05月04日9arxive

我创建了一个简单的 MFC .dll 文件,我可以通过另一个 MFC 应用程序访问它。我试图使用 Python 3.2.2 做同样的事情,但在我加载我的库后,它没有检测到我的 dll 中的函数并给出如下错误:

    Traceback (most recent call last): 
  File "<interactive input>", line 1, in <module> 
  File "C:\Python32\lib\ctypes\__init__.py", line 353, in __getattr__ 
    func = self.__getitem__(name) 
  File "C:\Python32\lib\ctypes\__init__.py", line 358, in __getitem__ 
    func = self._FuncPtr((name_or_ordinal, self)) 
AttributeError: function 'SayHello' not found 

..

我试图找到一个简单的程序来使用 Python 访问我的 MFC dll 文件,但到目前为止还没有成功。只是为了让大家知道,我已经阅读了 ctypes并且一直在寻找很多让这个工作。我的主要目标是使用 Python 作为脚本语言来与我的 MFC C++ dll 交互。我读了很多书,我能读到的最接近的书是 PythonWin。请在这方面提供帮助。

干杯。

请您参考如下方法:

我已经找到并解决了我的问题。对于那些可能期望在未来出现这种情况的人,我只想粘贴 python 脚本代码,以使您的函数可以在 python 脚本中访问。使用 C++ 函数的方法显然是在 .dll 文件中声明它。

extern "C" __declspec(dllexport) int SayHello(int strNo); 

你的 Python 脚本应该是这样的:(需要 getattr() 函数来访问你的 python 脚本中的 c++ 函数)

mydll = cdll.LoadLibrary("Location.dll") 
hellofunc = getattr(mydll,'SayHello') 
func2.restype = c_int 
func2.argtypes = [c_int] 
x = func2(34) 
print(x) 

...

如果大家觉得我说的不对,欢迎指正。我是 Python 的初学者,它以这种方式对我有用,之后我可以继续编写脚本。 希望这对其他人有帮助。

干杯。