【发布时间】:2014-09-20 16:53:49
【问题描述】:
我对 Python 做了一个 C 扩展。当我从 python 调用 writeByte(..) 时遇到问题。无论我在 python 中作为参数输入什么数字,当我在 C 函数中打印它时,该值都将为零。
test.py:
import myTest_1024LS
myTest_1024LS.findInterface()
myTest_1024LS.writeByte(0x01, 0x43)
setup.py:
from distutils.core import setup, Extension
module1 = Extension('myTest_1024LS',
include_dirs = ['/usr/local/include'],
libraries = ['hid'],
library_dirs = ['/usr/local/include', '/Home/NetBeansProjects/MCCDAQ/usb1024LS_with_py'],
sources = [ 'pmd.c', 'usb-1024LS.c', 'myTest_1024LS.c'],
language = 'c', )
setup (name = 'myTest_1024LS',
ext_modules = [module1])
myTest_1024LS.c:
void findInterface(void){
int interface;
hid_return ret;
ret = hid_init();
if (ret != HID_RET_SUCCESS) {
fprintf(stderr, "hid_init failed with return code %d\n", ret);
exit(1);
}
if ((interface = PMD_Find_Interface(&hid, 0, USB1024LS_PID)) >= 0) {
printf("USB 1024LS Device is found! interface = %d\n", interface);
} else if ((interface = PMD_Find_Interface(&hid, 0, USB1024HLS_PID)) >= 0) {
printf("USB 1024HLS Device is found! interface = %d\n", interface);
} else {
fprintf(stderr, "USB 1024LS and USB 1024HLS not found.\n");
exit(1);
}
}
void writeByte(__u8 port, __u8 byte){
printf("%x, %x\n", port, byte);
if((port==DIO_PORTA)||(port==DIO_PORTB)){
usbDOut_USB1024LS(hid, port, byte);
printf("You wrote 0x%x to port %x\n", byte, port);
}else if(port == DIO_PORTC){
printf("Port C is splitted into PORT C HIGH and LOW,\nthis means that your byte is separated into two nibbles before sending\n");
__u8 nib_low = byte & 0x0F;
__u8 nib_high = (byte & 0xF0)>>4;
usbDOut_USB1024LS(hid, DIO_PORTC_LOW, nib_low);
usbDOut_USB1024LS(hid, DIO_PORTC_HI, nib_high);
}else{
printf("Port is not intended for bytes\n");
exit(1);
}
}
PyDoc_STRVAR(myTest_1024LS__doc__, "myTes_1024LS point evaluation kernel");
PyDoc_STRVAR(findInterface__doc__, "find device");
PyDoc_STRVAR(writeByte__doc__, "write byte");
static PyMethodDef myTest_methods[] = {
{"findInterface", py_findInterface, METH_VARARGS, findInterface__doc__},
{"writeByte", py_writeByte, METH_VARARGS, writeByte__doc__},
{NULL, NULL}
};
PyMODINIT_FUNC initmyTest_1024LS(void){
Py_InitModule3("myTest_1024LS", myTest_methods, myTest_1024LS__doc__);
}
static PyObject *py_findInterface(PyObject *self, PyObject *args){
if(!PyArg_ParseTuple(args, "")){
return NULL;
}
findInterface();
return Py_BuildValue("i",0);
}
static PyObject *py_writeByte(PyObject *self, PyObject *args){
__u8 port=1, byte=4;
if(!PyArg_ParseTuple(args, "dd|i:writeByte", &port, &byte)){
return NULL;
}
writeByte((__u8)port, (__u8)byte);
return Py_BuildValue("i",0);
}
如您所见,在 writeByte 函数中,我首先打印端口和字节值,以检查值是否正确。到目前为止,当它们真的与零不同时,它们总是为零。 我也尝试将十进制值而不是十六进制值作为参数,但似乎没有帮助。
可能是数据类型的问题,但是我找不到...
在我开始这个 python/c 项目之前,C 代码已经在 C 主函数中进行了测试。
【问题讨论】:
-
您错误地使用了
PyArg_ParseTuple()。您期待两个强制性的double参数和一个可选的int参数。这似乎不是你真正需要的。 -
啊,谢谢!当然,我只是用“ii”代替......然后它起作用了,太棒了:)
-
我们能否将其作为答案。