How Python refers to DLL files

Source: Internet
Author: User
The examples in this article describe how Python references dll files. Share to everyone for your reference. The specific analysis is as follows:

The interface in calling DLL files in Python is relatively straightforward, as we have a Test.dll file, internally defined as follows:

extern "C" {int __stdcall Test (void* p, int len) {  return len;}}

In Python we can load the following two different ways

1.

Import Ctypesdll = ctypes.windll.LoadLibrary (' Test.dll ')

2.

Import Ctypesdll = cTYPES. Windll (' Test.dll ')

Where Ctypes.windll is an object of the Ctypes.windll class, it is already defined in the cTYPES module. There is a test interface in the Test.dll, which can be called directly with the DLL.

NRst = Dll.test () print nRst

Since two parameters are 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 pointers and lengths to the strings in Python.

#方法一: sbuf = ' aaaaaaaaaabbbbbbbbbbbbbb ' pStr = ctypes.c_char_p () pstr.value = Sbufpvoid = Ctypes.cast (PStr, ctypes.c_void_ p). Valuenrst = Dll.test (pVoid, Len (pstr.value))

#方法二: test = Dll.testtest.argtypes = [Ctypes.c_char_p, ctypes.c_int]test.restypes = Ctypes.c_intnrst = Test (sbuf, Len ( SBUF))

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

extern "C" {   int __cdecl test (void* p, int len)  {     return len;   }}

Because the interface defines a call in the cdecl format, it is also necessary to use the appropriate type in Python

1.

Import Ctypesdll = 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.

Import Ctypesdll = cTYPES. Cdll (' Test.dll ')

Hopefully this article will help you with Python programming.

  • 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.