How can I use a DLL file from Python?

前端 未结 7 1323
迷失自我
迷失自我 2020-11-22 16:06

What is the easiest way to use a DLL file from within Python?

Specifically, how can this be done without writing any additional wr

7条回答
  •  粉色の甜心
    2020-11-22 16:14

    Building a DLL and linking it under Python using ctypes

    I present a fully worked example on how building a shared library and using it under Python by means of ctypes. I consider the Windows case and deal with DLLs. Two steps are needed:

    1. Build the DLL using Visual Studio's compiler either from the command line or from the IDE;
    2. Link the DLL under Python using ctypes.

    The shared library

    The shared library I consider is the following and is contained in the testDLL.cpp file. The only function testDLL just receives an int and prints it.

    #include 
    ​
    extern "C" {
    ​
    __declspec(dllexport)
    ​
    void testDLL(const int i) {
        printf("%d\n", i);
    }
    ​
    } // extern "C"
    

    Building the DLL from the command line

    To build a DLL with Visual Studio from the command line run

    "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
    

    to set the include path and then run

    cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
    

    to build the DLL.

    Building the DLL from the IDE

    Alternatively, the DLL can be build using Visual Studio as follows:

    1. File -> New -> Project;
    2. Installed -> Templates -> Visual C++ -> Windows -> Win32 -> Win32Project;
    3. Next;
    4. Application type -> DLL;
    5. Additional options -> Empty project (select);
    6. Additional options -> Precompiled header (unselect);
    7. Project -> Properties -> Configuration Manager -> Active solution platform: x64;
    8. Project -> Properties -> Configuration Manager -> Active solution configuration: Release.

    Linking the DLL under Python

    Under Python, do the following

    import os
    import sys
    from ctypes import *
    
    lib = cdll.LoadLibrary('testDLL.dll')
    
    lib.testDLL(3)
    

提交回复
热议问题