【发布时间】:2015-03-26 09:59:59
【问题描述】:
我有一个包含两个函数的 c 文件。该文件使用 gcc 编译为 dll,然后使用 ctypes 从 python 调用。简单的函数try1() 工作正常,但是调用try2() 时,它会抛出一个
windows error: access violation when writing 0x0
我的猜测:从包含的库调用的 c 库函数存在一些问题:printf、strcpy 等。但是 malloc 和 strlen 工作正常...
我该如何解决这个问题?我究竟做错了什么?谢谢! 以下是代码摘录:
mylib.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int try1(int x)
{
return x+2;
}
int try2(int x)
{
char* str;
str = malloc(strlen("text")+1); // works
strcpy(str, "text"); // problematic line
printf("x: %i\n", x); // problematic line
free(str); // works
return x+2;
}
编译:
gcc -shared -o mylib.dll mylib.c -O3 -Wall
python 调用:
import ctypes
mylib = ctypes.cdll.mylib
print mylib.try1(5) # works fine, prints 7
print mylib.try2(5) #crashes with the access violation error, if the problematic lines are present.
【问题讨论】:
-
是的,谢谢,已更正。但这只是一个错误的输入,而不是问题。
-
您未修改的代码适用于我在 Windows 7 64 位和 Python 2.7.6 以及 Python 3.3.0 下的 mingw-gcc 4.7.2
-
当你说malloc有效时,你测试过返回值吗?
标签: python c dll ctypes access-violation