Problem calling DLL in Python ctype windows

Asked

Viewed 393 times

2

I’m having trouble calling a dll in Python... this giving the following error: Windowserror: Exception: access Violation Reading 0x026A65F0, sometimes works without giving this error but most do not work. I’m using it like this:

from ctypes import *

dll = cdll.LoadLibrary(".dll")

dll.funcao.artypes = (c_char_p, c_char_p, c_char_p, c_char_p)

dll.funcao.restypes = c_int

dll.funcao(cast(Nome_Arq,c_char_p), 

cast(Entrada,c_char_p),cast(iv,c_char_p),cast(chave,c_char_p))

main. h

extern "C" DLL_EXPORT int funcao(char * Entrada, char * Saida, char* iv, char* chave);

main.cpp

extern "C" DLL_EXPORT int funcao(char * Entrada, char * Saida, char * iv_aux, char* chave_aux){
}

1 answer

0

I would say that the problem is how you are converting your Python data to pass to C++ - You do not show how to declare your variables Entrada, iv and chave - but the ctypes.cast does not convert a Python string (or other object) to a C-compatible strinc. Probably Cast simply passes the address of the Python string object to C - and the C function on the other side will try to read the string until it finds a byte marked with the value \x00 - sometimes finds one in the valid memory chunk, and sometimes not ( and in such cases you have the above error) - but anyway your program in C will be reading garbage: bytes that have nothing to do with the data you want to pass.

To convert a byte string (in Python 3, an object "bytes") to a valid C string, simply call ctypes.c_char_p with the string. This will make a copy of the data, and will add a marker \x00 at the end of them.

In your code, the change is:

dll.funcao(c_char_p(Nome_Arq), c_char_p(Entrada), c_char_p(iv),c_char_p(chave))
  • Even after switching from to c_char_p(Input)... the same error occurred...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.