Problem when calling DLL in Python ctype windows

1

I'm having trouble calling a dll in Python ... is giving the following error: WindowsError: exception: access violation reading 0x026A65F0, sometimes works without giving this error but most do not work. I'm using this way:

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){
}
    
asked by anonymous 27.08.2016 / 21:50

1 answer

0

I'd say the problem lies in how you're converting your Python data to pass to C ++ - You do not show how you declare your variables Entrada , iv and chave - but ctypes.cast does not convert a Python string (or another object) to a C-compatible strin. Cast simply probably 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 it finds one in the valid memory stretch, and sometimes not (and in those cases, you have the above error) - but anyway your C program 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, a "bytes" object) to a valid C string, just call ctypes.c_char_p direct with the string. This will make a copy of the data, and will still add a \x00 marker to the end of it.

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))
    
29.08.2016 / 10:10