You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go编译的DLL无法被Python加载,报WinError 193错误求助

问题

尝试用Go编译生成DLL并在Python中调用,出现如下错误:

Python代码

import ctypes

hllDll = ctypes.WinDLL("./test.dll")
hllDll.Hello()

报错信息

Traceback (most recent call last):
  File "c:\Users\sangg\ColumnIntegrator\pythoncode.py", line 3, in <module>
    hllDll = ctypes.WinDLL("./test.dll")
  File "C:\Users\sangg\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1은(는) 올바른 Win32 응용 프로그램이 아닙니다(含义:"[WinError 193] %1 不是有效的Win32应用程序")

已确认环境均为64位:

  • GCC目标架构为x86_64-w64-mingw32
  • Go环境变量GOARCH=amd64
  • Python解释器为64位(platform.architecture()输出('64bit', 'WindowsPE'))

编译命令使用的是:

go build -buildmode=c-archive -o test.dll test/test.go

请问遗漏了什么,该如何解决?

解决方案

核心问题是使用了错误的编译模式:

  • -buildmode=c-archive生成的是静态库(.a格式),即便手动修改后缀为.dll,它本质也不是Windows动态链接库,因此Python加载时会判定为无效的Win32应用程序。
  • 要生成Python可加载的Windows DLL,必须使用-buildmode=c-shared参数。

正确操作步骤:

  1. 修改编译命令:
go build -buildmode=c-shared -o test.dll test/test.go

执行后会生成两个文件:test.dll(可加载的动态链接库)和test.h(C头文件,用于声明导出的函数签名)。

  1. 确保Go代码符合C调用规范:
    需要用//export 函数名注释标记要导出的函数,且函数参数、返回值必须是C兼容类型,示例代码:
package main

import "C"
import "fmt"

//export Hello
func Hello() {
    fmt.Println("Hello from Go DLL!")
}

func main() {
    // 空main函数,DLL不需要主入口,但Go编译要求main包必须包含main函数
}
  1. 重新编译后,用原Python代码加载调用即可正常运行。

内容的提问来源于stack exchange,提问作者salcan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:48:30