Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过ctypes将包含可变字符串的结构从Python发送到C_Python_Ctypes - Fatal编程技术网

通过ctypes将包含可变字符串的结构从Python发送到C

通过ctypes将包含可变字符串的结构从Python发送到C,python,ctypes,Python,Ctypes,我有一个在C端包含字符数组的结构 stuct s { int x; char buffer[100]; } 在python方面,我定义了 class myS(ctypes.Structure): _fields_ = [("x", c_int), ("buffer",type(create_string_buffer(100)))] 现在,当我 buf = create_string_buffer(64) s1 = myS(10,buf) 这给了我

我有一个在C端包含字符数组的结构

stuct s
{
    int x;
    char buffer[100];
}
在python方面,我定义了

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函数更改。如何操作?

您可以将常规Python字符串分配给100*c_字符字段:

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

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

下面是一个快速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.");
}
输出:

here is the contents of the string.
5

我还尝试用c_char*100代替类型(create_string_buffer(100)),得到了相同的输出。。当我在s1defn中将实际字符串放在myS中时,它是有效的,但当我将变量放在它的位置时,为什么它会产生问题呢。两者应该以相同的方式工作。@Sudip使用buf.value获取字符串。不客气!如果答案有用,请投票或接受。
here is the contents of the string.
5