PYTHON调用c++

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)

1.3 顺便来个结果贴图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值