Python Call DLL

Source: Internet
Author: User

Python is not very efficient to run, but we can call C functions or DLLs to improve efficiency.

The following simple write a DLL:

MyDll.h

  1   #ifndef MYDLL   2   #define  mydll 3   #ifdef my_dll   4   #define  My_dll extern "C" _declspec (dllimport)   #else  Span style= "color: #008080;" > 6   #define  my_dll extern "C" _declspec (dllexport)  7   #endif   8   9  my_dll int   fun ();  10  # endif  

MyDll.cpp

1 #include"MyDll.h"234int fun () 5 {6     return Ten ; 7 }

The DLL file is then generated using Python to invoke the fun function.

1  fromcTYPESImportWindll2 3 4 defDllfun ():5Ll=cdll. LoadLibrary ("E:\\mydll.dll")6     returnLl.fun ()7 8 9 if __name__=="__main__":Ten     Print(Dllfun ())

Output Result:

>>>
10
>>>

Ps:

① encountered an error: OSError: [Winerror 193]%1 is not a valid WIN32 application, which is caused by the use of 64-bit Python, If you want to solve this problem you can use 32-bit Python or compile a 64-bit DLL (the former should be a more compatible solution).

② in fact, I originally wrote in the fun function is "std::cout<<" PRINT "<<std::endl;", but the operation results are not output, the specific reason is unclear.

③ if it is an API in _stdcall format, change Cdll to Windll, otherwise the parameter function will appear: Valueerror:procedure probably called with too many arguments (8 bytes in Excess).

Python Call DLL

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.