【问题标题】:Building a DLL with MinGW and loading it with Python's ctypes module使用 MinGW 构建 DLL 并使用 Python 的 ctypes 模块加载它
【发布时间】:2013-05-19 00:08:05
【问题描述】:

我正在尝试构建一个可以使用 ctypes.windll.loadlibrary(...) 在 python 中加载的 C DLL

我可以按照http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs 的 MinGW 教程使用 C 创建一个 DLL 和一个客户端程序。

当我尝试在 python 中加载相同的 DLL 时出现错误:

OSError: [WinErrror 193] %1 is not a valid Win32 application

有人可以告诉我我做错了什么吗?

这里是文件:

noise_dll.h

#ifndef NOISE_DLL_H
#define NOISE_DLL_H

// declspec will identify which functions are to be exported when 
// building the dll and imported when 'including' this header for a client
#ifdef BUILDING_NOISE_DLL
#define NOISE_DLL __declspec(dllexport)
#else
#define NOISE_DLL __declspec(dllimport)
#endif

//this is a test function to see if the dll is working
// __stdcall => use ctypes.windll ...
int __stdcall NOISE_DLL hello(const char *s);

#endif  // NOISE_DLL_H

noise_dll.c

#include <stdio.h>
#include "noise_dll.h"

__stdcall int hello(const char *s)
{
    printf("Hello %s\n", s);
    return 0;
}

我使用以下方法构建 DLL:

gcc -c -D BUILDING_NOISE_DLL noise_dll.c
gcc -shared -o noise_dll.dll noise_dll.o -Wl,--out-implib,libnoise_dll.a

python 代码很简单:

import ctypes
my_dll = ctypes.windll.LoadLibrary("noise_dll")

我收到上述错误:“%1 不是有效的 Win32 应用程序”

我知道 DLL 并没有完全错误,因为如果我创建一个客户端文件:

noise_client.c

#include <stdio.h>
#include "noise_dll.h"

int main(void)
{
    hello("DLL");
    return 0;
}

并构建:

gcc -c noise_client.c
gcc -o noise_client.exe noise_client.o -L. -lnoise_dll

我得到了一个工作可执行文件。我对上面的代码、选项和预处理器指令中发生的所有事情都有一些了解,但是对于如何使用 .dll 文件和 .a 文件仍然有些模糊。我知道如果我删除 .a 文件,我仍然可以构建客户端,所以我什至不确定它的目的是什么。我所知道的是它是多个目标文件的某种存档格式

我可以 ctypes.windll.loadlibrary(...) 一个在 windows/system32 中找到的普通 windows DLL 没有问题。

最后一点: 我正在使用 64 位 python 3.3。我使用的是minGW tat的版本,自带推荐的安装程序(mingw-get-inst-20120426.exe)。我不确定它是否是 32 位的,或者是否重要。

谢谢!

【问题讨论】:

    标签: python dll mingw


    【解决方案1】:

    使用 32 位 python - 您的 DLL 可能未编译为 64 位代码。

    【讨论】:

    • 虽然这确实加载了 DLL,但它不允许在 DLL 中运行函数,在本例中为“hello”。它在 MSVC 下构建 DLL 时有效。但这并不是 MinGW 的完整解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2013-03-12
    • 2012-05-08
    • 2023-03-16
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多