【发布时间】:2015-06-20 12:23:45
【问题描述】:
Cython 等价于 c 定义
#define myfunc(Node x,...) SetNode(x.getattributeNode(),__VA_ARGS__)
我有一个 c api SetNode,它的第一个参数是结构类型节点的节点和 N 个变量(N 是从 0-N 的变量号)
这是一个解决此类问题的 c 示例
exampleAPI.c
#include<stdarg.h>
float sumN(int len,...){
va_list argp;
int i;
float s=0;
va_start(argp,len);
for(i=0;i<len;i++){
s+=va_arg(argp,int);
}
va_end(argp);
}
exampleAPI.h
#include<stdarg.h>
float sumN(int len,...)
examplecode.c
#include<stdarg.h>
#include"exampleAPI.h"
int len(float first,...){
va_list argp;
int i=1;
va_start(argp,first);
while(1){
if(va_arg(argp,float)==NULL){
return i
}
else{
i++;
}
}
va_end(argp);
}
#define sum(...) sumN(len(__VA_ARGS__),__VA_ARGS__)
正在调用
sum(1,2,3,4);
将返回 10.000000
sum(1.5,6.5);
将返回 8.00000
我需要一个 cython 替代 bellow c 定义而不是上面的例子 因为我有一个 C-API,它具有 SetNode 函数,它接受可变数量的参数,我想将它包装在 cython 中并从 python 调用
#define myfunc(Node x,...) SetNode(x.getattributeNode(),__VA_ARGS__)
这里 Node 是在 cython 中定义的一个类,它拥有一个 c 结构作为属性,getattributeNode() 是 Node 类的一个函数,它返回需要传递给 C-API 的 c 结构。
cdef extern "Network.h":
ctypedef struct node_bn:
pass
node_bn* SetNode(node_bn* node,...)
cdef class Node:
cdef node_bn *node
cdef getattributeNode(self):
return self.node
def setNode(self,*arg):
self.node=SetNode(self.node,*arg) # Error cannot convert python objects to c type
我尝试过的替代方法
cdef extern from "stdarg.h":
ctypedef struct va_list:
pass
ctypedef struct fake_type:
pass
void va_start(va_list, void* arg)
void* va_arg(va_list, fake_type)
void va_end(va_list)
fake_type int_type "int"
cdef extern "Network.h":
ctypedef struct node_bn:
pass
node_bn* VSetNode(node_bn* node,va_list argp)
cdef class Node:
cdef node_bn *node
cdef getattributeNode(self):
return self.node
cpdef _setNode(self,node_bn *node,...):
cdef va_list agrp
va_start(va_list, node)
self.node=VSetNode(node,argp)
va_end(va_list)
def setNode(self,*arg):
self._setNode(self.node,*arg)
当参数列表为空时工作正常
n = Node()
n.setNode() #This works
n.SetNode("top",1) # error takes exactly one argument given 3 in self._setNode(self.node,*arg)
如果有人可以建议与它等效的 cython,那就太好了。
【问题讨论】:
标签: c cython word-wrap variadic-functions