Python calls the DLL Method

Source: Internet
Author: User

It is relatively simple to call the interface in the DLL file in Python.CodeAs follows:

For example, we have a test. dll file, which is defined as follows:

Extern "C"
{

Int _ stdcall test (void * P, int Len)
{
Return Len;
}

}

In python, we can load data in the following two ways:

1.
Import ctypes
DLL = ctypes. Windll. loadlibrary ('test. dll ')

2.
Import ctypes
DLL = ctypes. Windll ('test. dll ')
Ctypes. Windll is an object of the ctypes. Windll class, which has been defined in the ctypes module. There is a test interface in test. dll, which can be called directly using DLL.

Nrst = DLL. Test ()
Print nrst
Two parameters need to be passed in the test interface. One is a void pointer, which points to a buffer zone. One is the length of the buffer. Therefore, we need to obtain the pointer and length of the string in Python.

# Method 1:
Sbuf = 'aaaaaaaaaabbbbbbbbbbbbbbbbbbbbb'
Pstr = ctypes. c_char_p ()
Pstr. value = sbuf
Pvoid = ctypes. Cast (pstr, ctypes. c_void_p). Value
Nrst = DLL. Test (pvoid, Len (pstr. Value ))
 
# Method 2:
Test = DLL. Test
Test. argtypes = [ctypes. c_char_p, ctypes. c_int]
Test. restypes = ctypes. c_int
Nrst = test (sbuf, Len (sbuf ))
If you modify the interface definition in test. dll as follows:

Extern "C"
{
Int _ cdecl test (void * P, int Len)
{
Return Len;
}
}

Because the interface defines a call in the cdecl format, the corresponding type must also be used in Python.

1.
Import ctypes
DLL = ctypes. cdll. loadlibrary ('test. dll ')
# Note: The test. o file is generally used in Linux. You can also use the following method:
# DLL = ctypes. cdll. loadlibrary ('test. o ')

2.
Import ctypes
DLL = ctypes. cdll ('test. dll ')

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lf8289/archive/2008/04/24/2322550.aspx

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.