这是我的第一篇文章,所以请放心。:)我对Python也有点陌生,但我喜欢我目前所看到的。我要做的是访问一个c库,它允许我通过Python打印到收据打印机。我使用ctype在Python中创建了一个包装器,除了两个函数之外,一切都很顺利。下面是他们的原型:
int C56_api_printer_write(int printer, unsigned char * data, int size, unsigned long timeout_ms);
int C56_api_printer_read(int printer, unsigned char * data, int size, unsigned long timeout_ms);我的问题是使用ctype对无符号字符指针进行写入和读取。我必须在Python中读入一个位图文件,并将数组传递给write函数,或者在读的情况下,我需要将该指针作为整数数组读入。
谢谢!
发布于 2012-03-03 10:41:15
好的,在Kyss的帮助下,我完成了这项工作。以下是我完成此问题的测试代码和结果:
我的test.c代码:
#include <stdio.h>
int test(unsigned char *test, int size){
    int i;
    for(i=0;i<size;i++){
        printf("item %d in test = %d\n",i, test[i]);
    }   
}
int testout(unsigned char *test, int *size){
   test[2]=237;
   test[3]=12;
   test[4]=222;
   *size = 5;
}
main () {
    test("hello", 5); 
    unsigned char hello[] = "hi";
    int size=0;
    int i;
    testout(hello,&size);
    for(i=0;i<size;i++){
        printf("item %d in hello = %d\n",i, hello[i]);
    }   
}我创建了一个main来测试我的c函数。下面是函数测试的输出:
item 0 in test = 104
item 1 in test = 101
item 2 in test = 108
item 3 in test = 108
item 4 in test = 111
item 0 in hello = 104
item 1 in hello = 105
item 2 in hello = 237
item 3 in hello = 12
item 4 in hello = 222然后我为共享进行了编译,所以它可以在python中使用:
gcc -shared -o test.so test.c下面是我在python代码中使用的代码:
from ctypes import *
lib = "test.so"
dll = cdll.LoadLibrary(lib)
testfunc = dll.test
print "Testing pointer input"
size = c_int(5)
param1 = (c_byte * 5)()
param1[3] = 235 
dll.test(param1, size)
print "Testing pointer output"
dll.testout.argtypes = [POINTER(c_ubyte), POINTER(c_int)]
sizeout = c_int(0)
mem = (c_ubyte * 20)() 
dll.testout(mem, byref(sizeout))
print "Sizeout = " + str(sizeout.value)
for i in range(0,sizeout.value):
    print "Item " + str(i) + " = " + str(mem[i])和输出:
Testing pointer input
item 0 in test = 0
item 1 in test = 0
item 2 in test = 0
item 3 in test = 235
item 4 in test = 0
Testing pointer output
Sizeout = 5
Item 0 = 0
Item 1 = 0
Item 2 = 237
Item 3 = 12
Item 4 = 222成功了!
我现在唯一的问题是根据输出的大小动态调整c_ubyte数组的大小。我已经发布了一个关于这个问题的单独问题。
谢谢你的帮助,凯斯!
发布于 2012-03-03 02:25:32
下面的内容对你有帮助吗?如果它给你错误或者我误解了你的问题,请告诉我:
size =
printer =
timeout =
data = (ctypes.c_ubyte * size)() # line 5
C56_api_printer_read(printer, data, size, timeout)
# manipulate data eg
data[3] = 7
C56_api_printer_write(printer, data, size, timeout)编辑:
关于第5行:另请参阅http://docs.python.org/library/ctypes.html的15.17.1.13和15.17.1.20节。
(ctypes.c_ubyte * size)给出了一个构造长度大小的ctype数组的函数。然后,在这一行中,我不带参数地调用函数,导致初始化为零。
https://stackoverflow.com/questions/9537460
复制相似问题