这篇文章主要介绍了Python调用C/C++动态链接库的方法,需要的朋友可以参考下
本文以实例讲解了Python调用C/C++ DLL动态链接库的方法,具体示例如下:
示例一:
首先,在创建一个DLL工程(本例创建环境为VS 2005),头文件:
//hello.h
#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif
extern "C"
{
HELLO_API int IntAdd(int , int);
}
CPP文件:
//hello.cpp
#define EXPORT_HELLO_DLL
#include "hello.h"
HELLO_API int IntAdd(int a, int b)
{
return a + b;
}
这里有两个注意点:
(1)弄清楚编译的时候函数的调用约定采用的__cdecl还是__stdcall,因为根据DLL中函数调用约定方式,Python将使用相应的函数加载DLL。
(2)如果采用C++的工程,那么导出的接口需要extern “C”,这样python中才能识别导出的函数。
我的工程中采用__cdecl函数调用约定方式进行编译链接产生hello.dll,然后Python中采用ctypes库对hello.dll进行加载和函数调用:
from ctypes import *
dll = cdll.LoadLibrary('hello.dll');
ret <