Error in using C SDK in python

0

I'm trying to use a SDK with python. I have multiple dll files in the SPK. My script:

import ctypes    
import os

malib = ctypes.WinDLL(os.path.join('D:\Downloads\Aura API\sdk\AURA_SDK.dll'))    
print(malib.GetClaymoreKeyboardLedCount(1)) #function in the dll

I get the error :

WindowsError: exception: access violation reading 0x00000005

I can use some of the functions normaly but for others I get this issue. Also there are different dll's in the SDK and I think the problem could come from the communication between these dll (I only open one of these dll in the script) also because function not working seem to be using the other dll or/and communication with the computer.

Thanks if you got advices

python
python-2.7
dll
sdk
asked on Stack Overflow Mar 25, 2018 by R.Reus • edited Mar 25, 2018 by DYZ

1 Answer

0

You haven't set the argtypes and restype for the functions you're calling.

This means that, instead of knowing what C types to convert your arguments to, ctypes has to guess based on the Python types you pass it. If it guesses wrong, you will either pass garbage, or, worse, corrupt the stack, leading to an access violation.

For example, imagine this C function:

void func(int64_t n, char *s);

If you do this:

lib = # however you load the library
lib.func(2, 'abc')

… then ctypes, it will convert that 2 to a 32-bit int, not a 64-bit one. If you're using a 32-bit Python and DLL, that means n will get the 2 and the pointer to 'abc' crammed into one meaningless number, and s will be an uninitialized pointer to some arbitrary location in memory that, if your lucky, won't be mapped to anything and will raise an access violation.

But if you first do this:

lib = # however you load the library
lib.func.argtypes = [ctypes.c_int64, ctypes.c_char_p]
lib.func.restype = None
lib.func(2, 'abc')

… then ctypes will convert the 2 to a 64-bit int, so n will get 2 and s will get 'abc' and everyone will be happy.

answered on Stack Overflow Mar 25, 2018 by abarnert

User contributions licensed under CC BY-SA 3.0