我有一个从linux加载.so文件的程序,运行良好,没有问题。 现在,我正在努力使程序跨平台。经过一段时间的努力,我成功地编译了一个dll文件来支持Windows,但是当我试图从ctypes加载时,我得到了以下错误:
"WindowsError: exception: access violation writing 0x0000000000000000"
似乎它甚至不能正确地将参数传递给我的c函数。我想我可能在转换Windows dll的c代码时犯了一些错误,或者python代码可能需要更多的工作来正确地加载dll并在Windows中使用它。我熟悉python,但对ctypes和C都是新手。我试着寻找我丢失的东西,但不知道该怎么办。:(
我又试了几次,找到了出错的地方,但还是不知道怎么解决。所以当dll函数试图调用内部的另一个dll函数时,我的问题就出现了。我已经更新了我的代码以包含该部分。在
我已经检查了另一个dll(“mylib.dll“)通过在主函数(在另一个具有相同调用约定的c代码中)内部调用initfunc,在我的c代码中调用可以正常工作mylib.dll“没问题。我想如果我想从dll函数内部调用一个dll函数,我可能需要做更多的事情?在
下面是我的linux和Windows的c代码,以及在python中如何调用它们。在
正如Antti建议的那样,我已经编辑了我的代码,使之成为最小的、完整的、可验证的示例。我对堆栈溢出还很陌生,一开始我不明白创建“最小、完整和可验证的示例”意味着什么。谢谢你的建议,对不起我的无知。现在我可以用下面的代码重现同样的问题。在
//header param_header.h
typedef struct MYSTRUCT MYSTRUCT;
struct MYSTRUCT
{
double param1;
double param2;
};
//mylib.c this was compiled as an .so(gcc mylib.c -fPIC -shared -o mylib.so) and .dll
#include "param_header.h"
#include <stdio.h>
#ifdef __linux__
int update_param(char *pstruct, char *paramname, double param)
#else
__declspec(dllexport) int update_param(char *pstruct, char *paramname, double param)
#endif
{
printf("Print this if function runs");
return 0;
}
//my_c_code.c --> this compiled again an .so & .dll and called by python ctypes
#include "param_header.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __linux__
#include <dlfcn.h>
#else
#include <windows.h>
#endif
#ifdef __linux__
MYSTRUCT *initfunc(flag, number, params, paramnames)
#else
__declspec(dllexport) MYSTRUCT *initfunc(flag, number, params, paramnames)
#endif
int flag;
int number;
double params[100];
char *paramnames[100];
{
int index;
int check;
MYSTRUCT *pstruct=(MYSTRUCT *)malloc(sizeof(MYSTRUCT));
memset(pstruct,0,sizeof(MYSTRUCT));
#ifdef __linux__
void *pHandle;
pHandle=dlopen("./mylib.so",RTLD_LAZY);
int(*update_param)(char*, char*, double) = dlsym(pHandle, "update_param");
#else
HINSTANCE pHandle;
pHandle=LoadLibrary("./mylib.dll");
int(__cdecl *update_param)(char*,char*, double);
FARPROC updateparam = GetProcAddress(pHandle, "update_param");
if (!updateparam)
{
check = GetLastError();
printf("%d\n", check);
}
update_param = (int(__cdecl *)(char*, char*, double))updateparam;
#endif
for (index=0;index < number;index++) {
(*update_param)((char*)pstruct, paramnames[index],params[index]); // <--this line fails only for the windows.
}
return pstruct;
}
下面是我访问函数的python代码。在
^{pr2}$我不确定这是否足够调试。。。但编译的代码与上面的“c”文件结合。我没有任何问题。。但是我得到了dll案例的错误。任何想法都会很感激。在
在修复了(Python)代码中的2个错误之后,我能够成功地运行它。我没有猜测你的错误是什么(我仍然认为这是一个找不到.dll的问题,可能是因为命名错误),我转而重新构造了代码。
我想指出的一点是ctypespage:[Python 3]: ctypes - A foreign function library for Python。在
标题。h:
dll0.c:
^{pr2}$dll1.c:
代码.py:
注意事项:
ctypes.c_char_p
(因为我使用的是Python3)输出:
呵呵!呵!呼!:)
相关问题 更多 >
编程相关推荐