Python Reference DLL file method

Source: Internet
Author: User

The example in this article describes Python's method of referencing DLL files. Share to everyone for your reference. The specific analysis is as follows:

Calling the interface in a DLL file in Python is simpler, as we have a Test.dll file, which is internally defined as follows:

?

1 2 3 4 5 6 7 extern "C" {int __stdcall Test (void* p, int len) {return len;}}

In Python we can load in the following two ways

1.

?

1 2 Import cTYPES DLL = ctypes.windll.LoadLibrary (' Test.dll ')

2.

?

1 2 Import ctypes dll = cTYPES. Windll (' Test.dll ')

Where Ctypes.windll is an object of the Ctypes.windll class, it has been defined in the cTYPES module. There is a test interface in Test.dll that can be invoked directly with a DLL

?

1 2 Nrst = Dll.test () print Nrst

Because two parameters need to be passed in the test interface, one is a pointer of type void, which points to a buffer. One is the length of the buffer. So we're going to get the pointer and the length of the string in Python

?

1 2 3 4 5 6 #方法一: sbuf = ' aaaaaaaaaabbbbbbbbbbbbbb ' pstr = ctypes.c_char_p () Pstr.value = Sbuf pvoid = Ctypes.cast (PStr, Ctypes.c_vo id_p). Value Nrst = Dll.test (pvoid, Len (pstr.value))

?

1 2 3 4 5 #方法二: test = dll.test Test.argtypes = [Ctypes.c_char_p, ctypes.c_int] test.restypes = ctypes.c_int nrst = Test (SBuf, Len (s BUF))

If you modify the interface in Test.dll, the definition is as follows:

?

1 2 3 4 5 6 7 extern "C" {int __cdecl test (void* p, int len) {return len;}}

Because the interfaces are defined in CDECL format calls, the corresponding type is also required in Python

1.

?

1 2 3 4 Import cTYPES DLL = ctypes.cdll.LoadLibrary (' Test.dll ') # #注: Generally under Linux for TEST.O files, you can also use the following methods: # #dll = Ctypes.cdll.LoadLibrary (' TEST.O ')

2.

?

1 2 Import ctypes dll = cTYPES. Cdll (' Test.dll ')

I hope this article will help you with your Python programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.