使用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#,"
......
当Linux内核在体系结构差异较大的平台之间移植时,会产生与数据类型相关的问题。
.在编译内核时使用 -Wall -W strict-prototypes 选项, 可以避免很多错误的发生
.内核使用的基本数据类型主要有:
int 标准C语言整数类型
&n ......
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 ......
在Python中的线程运行实际是受到Interpreter的控制或者说牵制的。在Interpreter的核心函数
PyObject * PyEval_EvalFrameEx
(PyFrameObject *f, int
throwflag)
我们可以看到有一个全局变量_Py_Ticker来控制着线程对Interpreter的占有的,默认是Interpreter每执行一百条指令就会释放另一个全局变量interpreter_lock.
......
设置:
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
......