Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a DLL function from Python

Tags:

python

dll

I want to call a function inside a DLL from Python. But I'm getting this error:

"Attribute Error function not found"

This is my code:

import os
import ctypes


os.chdir("C:\\Program Files\\Compact Automated Testing System V2.0")    

# Load DLL into memory. 
CATSDll = ctypes.WinDLL ("CATS.dll")

# Set up prototype and parameters for the desired function call. 
CATSDllApiProto = ctypes.WINFUNCTYPE (ctypes.c_uint8,ctypes.c_double) 

CATSDllApiParams = (1, "p1", 0), (1, "p2", 0), 

# Actually map the call (setDACValue) to a Python name.
CATSDllApi = CATSDllApiProto (("setDACValue", CATSDll), CATSDllApiParams)

# Set up the variables and call the Python name with them. 
p1 = ctypes.c_uint8 (1)
p2 = ctypes.c_double (4)

CATSDllApi(p1,p2)

But the DLL documentation shows a function setDACValue with ChannelId & DAC Voltage as the inputs.

The above is based on a piece of code available from StackOverflow.

I've also tried the simple method of using cdll.LoadLibrary & then calling the function, but that also gives the same error.

Can anyone suggest me what is wrong? Thanks.

Full Traceback:

Traceback (most recent call last):
  File "C:\Users\AEC_FULL\Softwares\eclipse\plugins\org.python.pydev_3.9.2.201502050007\pysrc\pydevd.py", line 2235, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "C:\Users\AEC_FULL\Softwares\eclipse\plugins\org.python.pydev_3.9.2.201502050007\pysrc\pydevd.py", line 1661, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Users\AEC_FULL\Saravanan\Workspace\CATS\CATS.py", line 18, in <module>
    CATSDllApi = CATSDllApiProto (("setDACValue", CATSDll), CATSDllApiParams)
AttributeError: function 'setDACValue' not found

Signature of the setDACValue

like image 357
user3561075 Avatar asked Apr 23 '15 13:04

user3561075


People also ask

Can Python read DLL?

Calling a dll from python pyd is nothing more than a DLL which python can use directly. If you have access to the source code for the external library, you can use SWIG (Simplified Wrapper Interface Generator) to compile this to a . pyd library which can be used directly in python.

Can Python compile to DLL?

Python embedding is supported in CFFI version 1.5, you can create a . dll file which can be used by a Windows C application.


1 Answers

When you specifiy prototype of function you should specify not only the types of arguments, but the return type as first arg to WINFUNCTYPE. Therefore, the line

CATSDllApiProto = ctypes.WINFUNCTYPE (ctypes.c_uint8,ctypes.c_double)

should be replaced with

CATSDllApiProto = ctypes.WINFUNCTYPE (ctypes.c_uint8, ctypes.c_uint8,ctypes.c_double)
like image 125
kvorobiev Avatar answered Oct 06 '22 20:10

kvorobiev