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