PYTHON调用c++
1.1 使用vs编译动态链接库dll
因为python使用c语言实现的,所以对于c++不太友好,要使用c++需要加上一下代码,类似告诉编译器用c来编译该c++代码。
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT
需要注意的是需要在配置管理器中选择"x64"的平台,编译出的dll文件才能够在python中引用。
其中一个函数的代码:
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT bool __stdcall Compress(char* src_path, char* target_path)
{
try {
FILE* File_src = fopen(src_path, "r");
FILE* File_compress = fopen(target_path, "w");
unsigned long len_src;
unsigned long len_compress;
unsigned char* buffer_src = new unsigned char[MaxBufferSize];
unsigned char* buffer_compress = new unsigned char[MaxBufferSize];
// 压缩文件:
len_src = fread(buffer_src, sizeof(char), MaxBufferSize - 1, File_src);
compress(buffer_compress, &len_compress, buffer_src, len_src);
fwrite(buffer_compress, sizeof(char), len_compress, File_compress);
fclose(File_src);
fclose(File_compress);
cout << "compress succeed!" << endl;
return true;
}
catch (const char* msg) {
cout << "falure!" << endl;
return false;
}
}
1.2 使用python引用dll文件
代码比较短,直接贴:
import ctypes
# 动态链接库所在目录
c_fun = ctypes.WinDLL('dll\\Dll2.dll')
# 三个文件的路径
src_path = ctypes.c_char_p(bytes('E:\\test.txt', 'GBK'))
compress_path = ctypes.c_char_p(bytes('E:\\compress.txt','GBK'))
uncompress_path = ctypes.c_char_p(bytes('E:\\uncompress.txt','GBK'))
# 声明函数返回值
c_fun.Compress.restype=ctypes.c_bool
c_fun.Uncompress.restype=ctypes.c_bool
# 将test.txt压缩成compress.txt
c_fun.Compress(src_path, compress_path)
# 将test.txt压缩成compress.txt后再解压成uncompress.txt
c_fun.Uncompress(src_path, uncompress_path)