【发布时间】:2020-07-30 11:32:33
【问题描述】:
我是 C++ 的初学者,一直在尝试通过 ctypes 使用 DLL 从 Python 访问 C++ 函数。
运行我的代码时,我总是收到错误 AttributeError: function 'my_function' not found。
头文件.h
#pragma once
int my_function(void);
源.cpp
#include "Header.h"
int my_function(void)
{
return(17); //test
}
ctypesTest.py
import ctypes
if __name__ == "__main__":
mydll = ctypes.CDLL("MyDLL.dll")
print(mydll.my_function())
每次我运行 Python 脚本时都会出现属性错误。
我只需要超出预期功能的值。
【问题讨论】:
-
也许这是因为你在函数声明周围缺少
extern "C"? -
您可能还需要使用
__declspec(dllexport)显式导出函数。我认为 Windows 默认不会从 DLL 导出函数。 -
@MikelRychliski 非常感谢。当我实施您的两个建议时,该程序起作用了。我为此困惑了好几个小时。
-
这个页面也有一些关于 Windows 和 Linux 的有用信息:wolfprojects.altervista.org/articles/dll-in-c-for-python