好的,在 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 数组的大小。不过,我已经发布了一个单独的问题。
感谢您的帮助凯斯!