上一篇中我们在python端的做法是每次读取一个数据块,然后将这个数据块传递进C扩展模块中去,但对于目标文件的数据写入是在C扩展模块中完成的,但其实可以更面向对象一点,不是吗?原来outfp是一个文件指针,
不如改成一个从Python中传递一个文件对象到C模块里去,这个文件对象有自己的write方法,这样在C扩展模块中你就可以回调文件对象的write方法来完成数据的写入。
首先来看Python端的代码,我们定义了一个file类继承下来的MyFile子类,其中的write方法就是为在C扩展模块中回调而专门准备的。
#!/usr/bin/env python

import clame

INBUFSIZE 
= 4096

class MyFile(file):

    
def __init__(self, path, mode):
        file.
__init__(self, path, mode)
        self.n 
= 0

    
def write(self, s):
        file.write(self, s)
        self.n 
+= 1

output 
= MyFile('test3.mp3''wb')
encoder 
= clame.Encoder(output)
input 
= file('test.raw''rb')

data 
= input.read(INBUFSIZE)
while data != '':
    encoder.encode(data)
    data 
= input.read(INBUFSIZE)

input.close()
encoder.close()
output.close()

print 'output.write was called %d times' % output.n

相关文章:

  • 2021-06-14
  • 2022-02-10
  • 2021-07-21
  • 2022-12-23
  • 2022-02-10
猜你喜欢
  • 2021-09-24
  • 2021-05-20
  • 2021-06-09
  • 2021-09-01
  • 2021-07-19
  • 2022-12-23
相关资源
相似解决方案