【问题标题】:Python ctypes dll call access violation when using library functions使用库函数时Python ctypes dll调用访问冲突
【发布时间】: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


【解决方案1】:

原来,问题是这样的: 我使用 cygwin 的内置 gcc 在 cygwin 中构建了 dll。它链接了 cygwin1.dll 运行时,而 python 的 ctypes 不知何故不能容忍这一点。 当我使用 MinGW 的 gcc 构建 dll 时,现在一切正常,因为它使用 Windows 运行时。

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2021-04-30
    • 2018-11-11
    相关资源
    最近更新 更多