使用C语言扩展Python(五)
上一篇中我们在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 再来看C模块的代码,clame_EncoderObject结构体中的outfp改成了PyObject类型的指针,相应的dealloc方法也做了调整,由于outfp是一个对象,因此需要对其引用计数进行减1操作,而以前的代码是直接调用fclose来直接关闭打开的目标文件。但现在我们只需要对其引用计数做减1操作,等到其为0的时候,在外部的python代码中就可以关闭这个文件对象。同样可以看到在init函数中有相应的引用计数加1的操作。在encode和close两个函数中,通过PyObject_CallMethod实现了对Python对象中指定方法的回调。代码#include <Python.h>
#include <lame.h>
/*
*
相关文档:
#include <stdio.h>
#include <string.h>
int
main(void)
{
char str[] =
"3BVPSq4xF.K?=u#,"
"G'K<MrDnRr7gH%#,"
"XKf<f%G`w^=?C<#,"
"HgU_AnNR?*PDQU#,"
......
c库函数详解——assert
函数名: assert
功 能: 测试一个条件并可能使程序终止
用 法: void assert(int test);
程序例:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
struct ITEM {
int key;
int value;
};
/* add item to ......
在上一篇中我们已经使用c语言实现了一个最简单的扩展模块,这一篇中将在其基础上进行功能的丰富。首先来考虑如何从外部的Python向C模块传递进参数,foo_bar2展示了如何向C模块传递整数,浮点数,字符串三个参数,其中"ids"指明了传入参数的数据类型。PyArg_ParseTuple负责对args进行解析,若解析失败则返回0.代码#include&n ......
设置:
1. Tools/Projects and Solutions/VC ++ Directories
Inlcude files: C:\Program Files\MATLAB\R2009a\extern\include
Library files: C:\Program Files\MATLAB\R2009a\extern\lib
2. Property
Configuration Properties/Linker
......