Using python to reference DLL files,

Source: Internet
Author: User

Using python to reference DLL files,

This example describes how to reference a DLL file in python. Share it with you for your reference. The specific analysis is as follows:

Calling the interface in the dll file in python is relatively simple. 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 ctypesdll = ctypes.windll.LoadLibrary( 'test.dll' )

2.

import ctypesdll = 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 = 'aaaaaaaaaabbbbbbbbbbbbbbbbb' pStr = ctypes. c_char_p () pStr. value = sBufpVoid = ctypes. cast (pStr, ctypes. c_void_p ). valuenRst = dll. test (pVoid, len (pStr. value ))
# Method 2: 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 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 ctypesdll = ctypes. cdll. loadLibrary ('test. dll ') # Note: Generally, test is used in linux. o file, you can also use the following method: # dll = ctypes. cdll. loadLibrary ('test. O ')

2.

import ctypesdll = ctypes.CDll( 'test.dll' )

I hope this article will help you with 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.