【问题标题】:ctypes can't find find dll functionctypes找不到find dll函数
【发布时间】: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

标签: python c++ dll ctypes


【解决方案1】:

@Mikel Rychliski 回答了我的问题。

头文件.h

#pragma once

#define DllExport __declspec( dllexport )

extern "C"
{
    __declspec(dllexport) int my_function(void);
}

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多