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”头文件?
1条答案
按热度按时间4urapxun1#
distutils
似乎错误地连接了msvc CRT。你不应该导入任何带下划线的东西,比如
_distutils
,因为它不是公共API的一部分,你不应该使用它。由于这是一个简单的windows dll,你可以直接调用
cl.exe
并编译它。(确保你打开x64 Native Tools Command Prompt for VS 2022
命令提示符之前,你这样做)字符串
这将工作,但如果你有更多的文件,那么你可能应该为它创建一个
cmake
项目,并使用它从python构建你的C dll。快速查看从
distutils
生成的dependencies。的数据
与直接来自
cl.exe
的一个相比。的
复制所有额外的依赖从windows sdk到dll文件夹应该得到它的工作,但这不是正确的方法。