Python Reference DLL file method

Source: Internet
Author: User
Tags in python

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

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.