python dict函数用法_如何将python中的dict作为参数传入c函数中用c做相关的处理?...

展开全部

#先上代码再解释

static PyObject *keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)

{

int voltage;

char *state = "a stiff";

char *action = "voom";

char *type = "Norwegian Blue";

static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,

&voltage, &state, &action, &type))

return NULL;

printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",

action, voltage);

printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

Py_INCREF(Py_None);

return Py_None;

}

static PyMethodDef keywdarg_methods[] = {

/* The cast of the function is necessary since PyCFunction values

* only take two PyObject* parameters, and keywdarg_parrot() takes

* three.

*/

{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,

"Print a lovely skit to standard output."},

{NULL, NULL, 0, NULL} /* sentinel */

};

PyObject * initkeywdarg(void)

{

/* Create the module and add the functions */

return Py_InitModule("keywdarg", keywdarg_methods);

}

这是一个函数(keywdarg_parrot)即使用了元组参数,也32313133353236313431303231363533e4b893e5b19e31333335333064使用了字典参数的例子。例子出自Python2.7.2的文档。具体在:

Python v2.7.2 documentation »Extending and Embedding the Python

Interpreter

这个页面下。文档里面有一些关于C/C++与Python交互的介绍和例子,还是比较详细的。传递字典参量要注意,{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,

"Print a lovely skit to standard output."},

这里的METH_VARARGS | METH_KEYWORDS,与普通的不同。解析用:PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,

&voltage, &state, &action, &type)

其中的四个变量要提前声明好,这里分别是int,str,str,str类型的。int对应的是args接受到的值。string的都是keywds里面的,它们都是有初始值的。kwlist是变量的名字,就是在python里调用的时候使用的keyword名称。照着例子的模式可以改成其它的,能用的。具体是怎么工作的,其实我也太明白。

Python代码是这样的调用的时候:print keywdarg.parrot(10,"LHJ",'HKJ','ER')

print keywdarg.parrot(10,"LHJ",'HKJ')

print keywdarg.parrot(10,"LHJ",type='KJ')

输出分别是:

-- This parrot wouldn't HKJ if you put 10 Volts through it.

-- Lovely plumage, the ER -- It's LHJ!

None

-- This parrot wouldn't HKJ if you put 10 Volts through it.

-- Lovely plumage, the Norwegian Blue -- It's LHJ!

None

-- This parrot wouldn't voom if you put 10 Volts through it.

-- Lovely plumage, the KJ -- It's LHJ!

None

第二次调用省略掉了变量,也能正常执行。第三次调用,变量type本来是第四位的,现在变成了keyword并写在了第三位,是python代码里调用的常见形式:keyword不讲顺序,省略掉的keyword使用了默认值。

就这些了,其它的你再看一下Python的文档吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值