751E 2023-10-22 14:38 采纳率: 0%
浏览 4

在python中调用c++库的内存管理

#如题,在python中调用c++库,但是处理文件数量比较多,会导致内存溢出,,想知道该怎么释放这个c库所占用的内训

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-10-22 17:28
    关注

    【相关推荐】



    • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/1091394
    • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:利用python或C++读取指定文件夹下的所有图片视频等
    • 您还可以看一下 李炳辰老师的《日内高频交易实战,从python数据分析到C++编写策略》课程中的 编写简单的策略进行测试小节, 巩固相关知识点
    • 除此之外, 这篇博客: 解决python调用c/c++的.so库的段错误问题,和python调c/c++库要点中的 执行完函数之后可以打印数组,就可以看到传出的字符串啦 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

      c/c++接口代码:

      int Example(char file[] ,char* Buf,int *len)

      {    

          char ch[] = "hello world";
          memcpy(buf, ch, strlen(ch));
          *len = strlen(ch);

          printf("%s\n",file);

      }

       

      python 代码:

      import ctypes
      from ctypes import *
      def convert_type(input):
          ctypes_map = {int:ctypes.c_int,
                    float:ctypes.c_double,
                    str:ctypes.c_char_p
                    }
          input_type = type(input)
          if input_type is list:
              length = len(input)
              if length==0:
                  print("convert type failed...input is "+input)
                  return null
              else:
                  arr = (ctypes_map[type(input[0])] * length)()
                  for i in range(length):
                      arr[i] = bytes(input[i],encoding="utf-8") if (type(input[0]) is str) else input[i]
                  return arr
          else:
              if input_type in ctypes_map:
                  return ctypes_map[input_type](bytes(input,encoding="utf-8") if type(input) is str else input)
              else:
                  print("convert type failed...input is "+input)
                  return null
      libtestso = cdll.LoadLibrary("./ReadFile.so")
      file ="result"
      Len = 123
      Buf = create_string_buffer(0, Len)
      c_bufLen = c_int(Len)

      //传入字符串file ,Buf是传出字符串,c_bufLen是传出字符串的长度
      libtestso.Example(convert_type(file),Buf,byref(c_bufLen))

      print(c_bufLen.value)

      print(string_at(Buf))

       

      这时应会打印

      result

      hello world

       

       

       


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 10月22日

悬赏问题

  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题