易截截图软件、单文件、免安装、纯绿色、仅160KB

使用C语言扩展Python(二)

在上一篇中我们已经使用c语言实现了一个最简单的扩展模块,这一篇中将在其基础上进行功能的丰富。首先来考虑如何从外部的Python向C模块传递进参数,foo_bar2展示了如何向C模块传递整数,浮点数,字符串三个参数,其中"ids"指明了传入参数的数据类型。PyArg_ParseTuple负责对args进行解析,若解析失败则返回0.代码#include <Python.h>
static PyObject* foo_bar(PyObject* self, PyObject* args) {
    Py_RETURN_NONE;
}
static PyObject* foo_bar2(PyObject* self, PyObject* args) {
    int iNum;
    double fNum;
    char* str;
    if (!PyArg_ParseTuple(args, "ids", &iNum, &fNum, &str)) {
        return NULL;
    }
    Py_RETURN_NONE;
}
static PyMethodDef foo_methods[] = {
    {"bar",(PyCFunction)foo_bar,METH_NOARGS,NULL},
    {"bar2", (PyCFunction)foo_bar2,METH_VARARGS,NULL},
    {NULL,NULL,0,NULL}
};
PyMODINIT_FUNC initfoo() {
    Py_InitModule3("foo", foo_methods, "My first extension module.");
} 你还可以指定可选的参数,只需要通过在格式字符串中包含一个"|"字符即可,如下所示:代码static PyObject* foo_bar2(PyObject* self, PyObject* args) {
    int iNum;
    double fNum;
    char* str;
    int iNum2 = 4;
    double fNum2 = 5.0;
    char *str2 = "hello";
    if (!PyArg_ParseTuple(args, "ids|ids", &iNum, &fNum, &str,&iNum2, &fNum2, &str2)) {


相关文档:

C\C++ byte或者char数组转int值

假设有char a[2];
如要把a转换为int值。应是如下写法int b=*(int *)a;
即,先把指针a 转换为一个int指针,然后再此基础上取值。
但是另一种写法 int b=(int)(*a);是不对的,*a 取a的内存单元内容,因为现在a是char指针,所以只会取a[1]中内容,最大为255. 这里要说明的是,在把char或byte数组转换为其他类型的值时,要先 ......

C版《生日快乐》

#include<windows.h>

void Birthday();

int main()
{
Birthday();
return 0;
}

void Birthday()
{
unsigned frequency[]={392,392,440,392,523,494,

392,392,440,392,587,523,

......

C程序员的情书

#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程序员的情书

#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 c 数据类型

当Linux内核在体系结构差异较大的平台之间移植时,会产生与数据类型相关的问题。
.在编译内核时使用 -Wall  -W strict-prototypes 选项, 可以避免很多错误的发生
.内核使用的基本数据类型主要有:
     int           标准C语言整数类型
&n ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号