Ctypes WindowsError:异常:从另一个DLL fi调用DLL函数时写入0x0000000000000000的访问冲突

2024-10-03 23:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从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案例的错误。任何想法都会很感激。在


Tags: 函数代码indexincludeparamlinuxupdateint
1条回答
网友
1楼 · 发布于 2024-10-03 23:18:34

在修复了(Python)代码中的2个错误之后,我能够成功地运行它。我没有猜测你的错误是什么(我仍然认为这是一个找不到.dll的问题,可能是因为命名错误),我转而重新构造了代码。
我想指出的一点是ctypespage:[Python 3]: ctypes - A foreign function library for Python。在

标题。h

#if defined(_WIN32)
#define GENERIC_API __declspec(dllexport)
#else
#define GENERIC_API
#endif

#define PRINT_MSG_0() printf("From C - [%s] (%d) - [%s]\n", __FILE__, __LINE__, __FUNCTION__)


typedef struct STRUCT_ {
    double param1;
    double param2;
} STRUCT;

dll0.c

^{pr2}$

dll1.c

#include "header.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(_WIN32)
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#define DLL1_API GENERIC_API
#define UPDATE_PARAM_FUNC_NAME "updateParam"


typedef int(__cdecl *UpdateParamFuncPtr)(char*, char*, double);


DLL1_API STRUCT *initFunc(flag, number, params, paramnames)
    int flag;
    int number;
    double params[100];
    char *paramnames[100];
{
    int index = 0;
    UpdateParamFuncPtr updateParam = NULL;
    STRUCT *pStruct = (STRUCT*)malloc(sizeof(STRUCT));
    memset(pStruct, 0, sizeof(STRUCT));

#if defined(_WIN32)
    HMODULE pHandle = LoadLibrary("./dll0.dll");
    if (!pHandle) {
        printf("LoadLibrary failed: %d\n", GetLastError());
        return NULL;
    }
    updateParam = (UpdateParamFuncPtr)GetProcAddress(pHandle, UPDATE_PARAM_FUNC_NAME);
    if (!updateParam) {
        printf("GetProcAddress failed: %d\n", GetLastError());
        FreeLibrary(pHandle);
        return NULL;
    }
#else
    void *pHandle = dlopen("./dll0.so", RTLD_LAZY);
    if (!pHandle) {
        printf("dlopen failed: %s\n", dlerror());
        return NULL;
    }
    updateParam = dlsym(pHandle, UPDATE_PARAM_FUNC_NAME);
    if (!updateParam) {
        printf("dlsym failed: %s\n", dlerror());
        dlclose(pHandle);
        return NULL;
    }
#endif
    PRINT_MSG_0();
    for (index = 0; index < number; index++) {
        (*updateParam)((char*)pStruct, paramnames[index], params[index]);
    }
#if defined(_WIN32)
    FreeLibrary(pHandle);
#else
    dlclose(pHandle);
#endif
    return pStruct;
}


DLL1_API void freeStruct(STRUCT *pStruct) {
    free(pStruct);
}

代码.py

#!/usr/bin/env python3

import sys
import traceback
from ctypes import c_int, c_double, c_char_p, \
    Structure, CDLL, POINTER


class Struct(Structure):
    _fields_ = [
        ("param1", c_double),
        ("param2", c_double),
    ]


StructPtr = POINTER(Struct)

DoubleArray100 = c_double * 100
CharPArray100 = c_char_p * 100


def main():
    dll1_dll = CDLL("./dll1.dll")
    init_func_func = dll1_dll.initFunc
    init_func_func.argtypes = [c_int, c_int, DoubleArray100, CharPArray100]
    init_func_func.restype = StructPtr
    free_struct_func = dll1_dll.freeStruct
    free_struct_func.argtypes = [StructPtr]
    param_dict = {
        b"a": 1,
        b"b": 2,
    }
    params = DoubleArray100(*param_dict.values())
    paramnames = CharPArray100(*param_dict.keys())
    flag = 1
    number = len(param_dict)
    out = init_func_func(flag, number, params, paramnames)
    print(out)
    try:
        struct_obj = out.contents
        for field_name, _ in struct_obj._fields_:
            print("    {:s}: {:}".format(field_name, getattr(struct_obj, field_name)))
    except:
        traceback.print_exc()
    finally:
        free_struct_func(out)
    print("Done.")


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

注意事项

  • 做了一些重构
    • 重命名:文件、变量。。。(以“我的”开头的名字会让我头疼)
    • 试图避免代码重复(这可以改进得更多)-在公共区域(如文件、变量等)提取代码
    • 其他不重要的东西
  • 添加了一个freeStruct函数,该函数将释放initFunc返回的指针,否则将存在内存泄漏
  • C
    • 没有在Lnx上测试(没有启动VM),但它应该可以工作
    • 如果出现错误(GetProcAddress返回NULL),则退出initFunc而不仅仅是打印消息并继续。这是访问违规的一个很好的候选者
    • 退出initFunc之前卸载(内部).dll
    • 颠倒了LnxWin条件逻辑(WIN32dlfcn函数对于所有Nixes都是通用的(例如,如果您尝试在OSXSolaris上构建代码,那么dlfcn就不是了定义),它将落在Win分支上,并且明显失败)
  • Python
    • 删除np。代码不是用它编译的,而且绝对没有必要
    • 参数键从str更改为字节以匹配ctypes.c_char_p(因为我使用的是Python3

输出

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>"c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x64

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>dir /b
code.py
dll0.c
dll1.c
header.h
original_code_dir

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>cl /nologo /DDLL /MD dll0.c  /link /NOLOGO /DLL /OUT:dll0.dll
dll0.c
   Creating library dll0.lib and object dll0.exp

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>cl /nologo /DDLL /MD dll1.c  /link /NOLOGO /DLL /OUT:dll1.dll
dll1.c
   Creating library dll1.lib and object dll1.exp

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>dir /b
code.py
dll0.c
dll0.dll
dll0.exp
dll0.lib
dll0.obj
dll1.c
dll1.dll
dll1.exp
dll1.lib
dll1.obj
header.h
original_code_dir

(py35x64_test) e:\Work\Dev\StackOverflow\q053909121>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32

From C - [dll1.c] (56) - [initFunc]
From C - [dll0.c] (9) - [updateParam]
From C - [dll0.c] (9) - [updateParam]
<__main__.LP_STRUCT object at 0x000001B2D3AA80C8>
    param1: 0.0
    param2: 0.0
Done.

呵呵!呵!呼!:)

相关问题 更多 >