【问题标题】:Python: simple ctypes dll load yields errorPython:简单的 ctypes dll 加载会产生错误
【发布时间】:2012-04-15 16:29:59
【问题描述】:

我从 MSDN DLL example 创建了 MathFuncsDll.dll 并运行调用 .cpp 工作正常。现在,尝试在 IPython 中使用类似的 ctype 加载它

import ctypes
lib = ctypes.WinDLL('MathFuncsDll.dll')

在正确的文件夹中产生

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 28: ordinal not in range(128)

类似地在 Python shell 中产生

WindowsError: [Error 193] %1 is not a valid Win32 application

我应该改变什么?嗯,它可能是 Win 7 64 位与一些 32 位 dll 之类的,对吗?有时间我再看看。

【问题讨论】:

    标签: python dll ctypes windowserror


    【解决方案1】:

    ctypes 不适用于编写 MathFuncsDLL 示例的 C++。

    相反,用 C 编写,或者至少导出一个“C”接口:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    __declspec(dllexport) double Add(double a, double b)
    {
        return a + b;
    }
    
    #ifdef __cplusplus
    }
    #endif
    

    另请注意,调用约定默认为__cdecl,因此请使用CDLL 而不是WinDLL(使用__stdcall 调用约定):

    >>> import ctypes
    >>> dll=ctypes.CDLL('server')
    >>> dll.Add.restype = ctypes.c_double
    >>> dll.Add.argtypes = [ctypes.c_double,ctypes.c_double]
    >>> dll.Add(1.5,2.7)
    4.2
    

    【讨论】:

    • 谢谢,我在尝试加载 DLL 时根本没有区分 C 和 C++。所以必须分别考虑 C、C++ 和 C#,以及普通、.Net 和其他风格?那是 C 的 ctypes,也许是 C++ 的 Boost 和 .Net/C# DLL 的 pythonnet,对吧?
    • 是的,每种都有不同的解决方案。仅供参考,如果答案对您有用,请在 StackOverflow 上投票和/或使用答案左侧的箭头/检查将其作为您问题的答案。
    • 啊,谢谢你的建议;我不知道如何承认你的回答。我无法投票,我的声誉太低了。我假设如果我有源代码,我只能为 C++ DLL 提供 C 接口。或者对于我无法访问其源代码的第 3 方 DLL,这是否也是可能的?
    • 我使用 SWIG 连接到 C++ DLL。对于简单的对象接口来说,它可能会变得复杂,但它非常强大。它基本上写了一个 C 接口层和一个 python 代理库,让它看起来又像 C++ 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 2014-06-03
    • 2012-09-04
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多