【发布时间】:2013-04-27 08:01:14
【问题描述】:
我的环境:Windows Vista 64、Python3.1、Visual Studio 2008 sp1
错误描述: 我正在尝试使用 ctype 包装一个 dll(例如 Lib.dll),当继续执行 Lib.dll 中的一个函数(例如 func())时,发生错误:
"WindowsError: exception: access violation reading"
我认为 func() 和以前写在我的 '.py' 文件中的 Lib.dll 函数之间的不同之处在于 func() 包含一个 DOUBLE 类型参数,但我确信该参数传递正确,因为我已使用c_double() 进行投射。并且似乎在输入func() 时出现错误,因为func() 中的第一个代码(printf()) 没有执行。
我也试过在C环境下运行同一个dll及其函数,运行流畅。
更多信息:
lib.dll 在 MSVC 中编译(使用 extern "C"),我使用 CDLL 作为调用类型。问题实际上发生在另一个 dll (lib2.dll) 中的函数上。我使用 lib.dll 只是因为 lib2.dll 是用 C++ 编写的,并且我在 lib2 中包装了我想要的函数。它看起来像这样:
///////////////////////////////////
// lib.cpp
lib2 l;
void func(char * c1, char * c2, double d)
{
printf("%s, %s, %f\n", c1, c2, d); // All the parameters are passed correctly
l.func(c1, c2, d); // THIS IS where the error occurred
}
///////////////////////////////////
// lib2.cpp
void lib2::func(char * c1, char * c2, double d)
{
printf(); // The error happened before this line being executed.
...
}
///////////////////////////////////
And python script looks like this:
// my.py
dll = cdll.LoadLibrary("lib.dll")
dll.some_func1(c_char_p('a'))
dll.some_func2(c_char_p('b'))
func(c_char_p('c1'), c_char_p('c2'), c_double(1.1))
////////////////////////////////////
当我使用 ctype 加载 lib2.dll 时,它也无法工作,这也很奇怪。它显示未找到该功能。所以我必须使用 lib.dll 来调用 lib2.dll 中的函数。
谁能给我一些提示?谢谢
【问题讨论】:
-
放一些代码。
from ctypes import *... -
这是我对为什么不能直接调用 lib2.dll 的猜测:en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B
-
谢谢回复。我知道在 MSVC 中编译时,如果没有 extern "C" 或 .def 文件,名称将被破坏,并且 func() 会变成类似 '_func@YZ' 的东西。但即使我使用那些(.def 等),或者使用 'func = getattr(lib2, '_func@YZ')',它仍然不起作用。
-
顺便说一句,我可以在 MSVC 的另一个项目中加载没有 lib2.lib 的 lib2.dll,使用 loadlibrary(),它可以工作。
-
在致电
func之前尝试dll.func.argtypes = [c_char_p,c_double]。此外,您的func电话有两个c_char_p,但应该只有一个。
标签: python dll ctypes windowserror