1. Create a new C ++ source file named hello. cpp:
Cpp Code
# Include <stdio. h>
# Define DLLEXPORT extern "C" _ declspec (dllexport)
DLLEXPORT int _ stdcall hello ()
{
Printf ("Hello world! \ N ");
Return 0;
}
# Include <stdio. h>
# Define DLLEXPORT extern "C" _ declspec (dllexport)
DLLEXPORT int _ stdcall hello ()
{
Printf ("Hello world! \ N ");
Return 0;
}
2. compile it into a dll file:
Cpp Code
Cl/LD hello. cpp
Cl/LD hello. cpp
Note that the parameter here is/LD instead of/DL.
3. Compile a python file named hello. py:
Python code
# Coding: UTF-8
Import OS
Import ctypes
CUR_PATH = OS. path. dirname (_ file __)
If _ name _ = '_ main __':
Print 'starting ...'
Dll = ctypes. WinDLL (OS. path. join (CUR_PATH, 'Hello. dll '))
Dll. hello ()
# Coding: UTF-8
Import OS
Import ctypes
CUR_PATH = OS. path. dirname (_ file __)
If _ name _ = '_ main __':
Print 'starting ...'
Dll = ctypes. WinDLL (OS. path. join (CUR_PATH, 'Hello. dll '))
Dll. hello ()
4. Output:
Python code
Starting...
Hello world!
Starting...
Hello world!
Note:
1. the interface functions in C ++ dll must be prefixed with extern "C" _ declspec (dllexport) and C must be prefixed with _ declspec (dllexport.
Otherwise, an error is reported:
Python code
Traceback (most recent call last ):
File "hello. py", line 12, in <module>
Dll. hello ()
File "C: \ Python25 \ lib \ ctypes \__ init _. py", line 361, in _ getattr __
Func = self. _ getitem _ (name)
File "C: \ Python25 \ lib \ ctypes \__ init _. py", line 366, in _ getitem __
Func = self. _ FuncPtr (name_or_ordinal, self ))
AttributeError: function 'hello' not found
Traceback (most recent call last ):
File "hello. py", line 12, in <module>
Dll. hello ()
File "C: \ Python25 \ lib \ ctypes \__ init _. py", line 361, in _ getattr __
Func = self. _ getitem _ (name)
File "C: \ Python25 \ lib \ ctypes \__ init _. py", line 366, in _ getitem __
Func = self. _ FuncPtr (name_or_ordinal, self ))
AttributeError: function 'hello' not found www.2cto.com
2. Do I use ctypes. CDLL or ctypes. WinDLL?
Anyway, I cannot tell clearly, so the _ stdcall is explicitly added to the interface function in the dll. It seems that one is caller clear stack, and the other is callee clear.
In MSDN, the introduction of _ stdcall and _ cdecl is as follows:
_ Cdecl:
Http://msdn.microsoft.com/en-us/library/zkwh89ks (VS.80). aspx
This is the default calling convention for C and C ++ programs. because the stack is cleaned up by the caller, it can do vararg functions. the _ cdecl calling convention creates larger executables than _ stdcall, because it requires each function call to include stack cleanup code. the following list shows the implementation of this calling convention.
_ Stdcall:
Http://msdn.microsoft.com/en-us/library/zxk0tw93 (VS.71). aspx
The _ stdcall calling convention is used to call Win32 API functions. The callee cleans the stack, so the compiler makes vararg functions _ cdecl.