2012-04-04 25 views
2

我有包含C侧含有可变的字符串至C在Python通ctypes的发送stucture

stuct s 
{ 
    int x; 
    char buffer[100]; 
} 

和我蟒侧字符数组的结构我定义

class myS(ctypes.Structure): 
    _fields_ = [("x", c_int), 
     ("buffer",type(create_string_buffer(100)))] 

现在,当我做

buf = create_string_buffer(64) 
s1 = myS(10,buf) 

它给了我错误

TypeError: expected string or Unicode object, c_char_Array_100 found 

我想要一个将被我的C函数改变的字符串。怎么做?

+0

我也曾尝试c_char * 100到位类型(create_string_buffer(100))导致相同的输出。 – Sudip 2012-04-04 07:43:30

回答

1

您不必创建缓冲区。当您实例化缓冲区时,该缓冲区位于结构中。

下面是一个简单的DLL:

#include <string.h> 

struct s 
{ 
    int x; 
    char buffer[100]; 
}; 

__declspec(dllexport) void func(struct s* a) 
{ 
    a->x = 5; 
    strcpy(a->buffer,"here is the contents of the string."); 
} 

而这里的Python代码来调用它:

import ctypes 

class myS(ctypes.Structure): 
    _fields_ = [ 
     ("x", ctypes.c_int), 
     ("buffer",ctypes.c_char * 100)] 

s1 = myS() 
dll = ctypes.CDLL('test') 
dll.func(ctypes.byref(s1)) 
print s1.buffer 
print s1.x 

输出:

here is the contents of the string. 
5 
+0

谢谢mark ..我不知道.. – Sudip 2012-04-04 09:41:20

+0

不客气!如果答案是有用的投票或接受它。 – 2012-04-04 14:41:42

1

您可以在常规的Python字符串赋值给一个100 * c_char领域:

class myS(ctypes.Structure): 
    _fields_ = [("x", c_int), 
     ("buffer", 100*c_char)] 

s1 = myS(10, "foo") 
s1.buffer = "bar" 

但是,如果你有一个字符串缓冲区对象,你可以把它的值:

buf = create_string_buffer(64) 
s1 = myS(10,buf.value) 

>>> type(create_string_buffer(100)) == 100*c_char 
True 
+0

感谢janne ..它的工作,当我把实际的字符串放在s1里面的myS中,但是为什么当我把变量放在它的位置时它会产生问题。两者都应该以相同的方式工作.. – Sudip 2012-04-04 09:39:57

+0

@Sudip使用buf.value获取字符串。 – 2012-04-04 11:15:55