windows 从Python编译的C DLL调用简单的“Hello World!”函数会导致OSError:exception:access violation

xkrw2x1b  于 2023-11-21  发布在  Windows
关注(0)|答案(1)|浏览(219)

C代码:

// my_module.c

#include <stdio.h>

__declspec(dllexport)
void hello() {
    printf("Hello World!\n");
}

__declspec(dllexport)
int add_numbers(int a, int b) {
    return a + b;
}

// entry point
int main() {
    return 0;
}

字符串
build script:

# build.py

from setuptools._distutils.ccompiler import new_compiler

compiler = new_compiler()
compiler.compile(["my_module.c"])
compiler.link_shared_lib(["my_module.obj"], "my_module")


主脚本:

# main.py

import ctypes

my_module = ctypes.CDLL("./my_module.dll")

my_module.add_numbers.argtypes = ctypes.c_int, ctypes.c_int
my_module.add_numbers.restype = ctypes.c_int

my_module.hello.argtypes = ()
my_module.hello.restype = None

result = my_module.add_numbers(3, 4)
print(type(result), result)

my_module.hello()


运行python build.py后,dll创建没有问题。然而,当运行python main.py时,“add_numbers”函数工作,但调用“hello”函数会导致“OSError:exception:access violation writing 0x00000000002C44”。
我是否遗漏了什么?我是否需要告诉编译器包含“stdio.h”头文件?

4urapxun

4urapxun1#

distutils似乎错误地连接了msvc CRT。
你不应该导入任何带下划线的东西,比如_distutils,因为它不是公共API的一部分,你不应该使用它。
由于这是一个简单的windows dll,你可以直接调用cl.exe并编译它。(确保你打开x64 Native Tools Command Prompt for VS 2022命令提示符之前,你这样做)

cl.exe /LD my_module.c

字符串
这将工作,但如果你有更多的文件,那么你可能应该为它创建一个cmake项目,并使用它从python构建你的C dll。
快速查看从distutils生成的dependencies


的数据
与直接来自cl.exe的一个相比。



复制所有额外的依赖从windows sdk到dll文件夹应该得到它的工作,但这不是正确的方法。

相关问题