繁体   English   中英

Python ctypes设置c_char_p基础值

[英]Python ctypes set c_char_p underlying value

我有一个指向结构的指针。 在该结构中,其中一个字段是POINTER(c_char) 我正在尝试设置基础值,以便更改反映在具有指向同一地址的指针的任何其他应用程序中。

class foo(Structure):
    _fields_ = [("bar", POINTER(c_char)),
                 ("bazaz" c_int),
                 ...morefields]

z = .... # z is a pointer to a foo

# legal but doesn't do what I expect, this seems to set the pointer itself, not the underlying contents
z.contents.bar = b"asdfasdf" 

这显示“仅在python方面”。 但是,正在查看bar的C进程没有得到反映的更改。

如何“管理” bar以便我可以设置它,并且该更改会反映在具有指向同一地址的指针的任何其他应用程序中?

您需要使用docs中描述的create_string_buffer

但是,您应该小心,不要将它们传递给期望指向可变内存的函数。 如果你需要可变内存块,ctypes有一个create_string_buffer()函数,它以各种方式创建它们。

所以在你的情况下,你想要做的事情如下:

z.contents.bar = create_string_buffer(b"My string", 10)

这点bar到新的缓冲区,然后你应该能够改变通过的内容.value 对于Unicode( c_wchar ),请使用create_unicode_buffer

从注释中,您有一个返回POINTER(foo)实例的函数。 这是一个读取返回值并进行更改的工作示例。 如果您的代码仍无效,请创建一个类似的示例来重现该问题:

test.c的

#include <stdlib.h>
#include <string.h>

struct foo
{
    char* bar;
};

__declspec(dllexport) struct foo* func()
{
    /* This leaks memory, but is just an example... */
    struct foo* f = malloc(sizeof(struct foo));
    f->bar = malloc(20);
    strcpy(f->bar,"abcdefghijklmnop");
    return f;
}

test.py

from ctypes import *

class foo(Structure):
    _fields_ = ('bar',c_char_p),

dll = CDLL('test')
dll.func.argtypes = ()
dll.func.restype = POINTER(foo)

f = dll.func()
print(f.contents.bar)
f.contents.bar = b'abcd'
print(f.contents.bar)

输出:

b'abcdefghijklmnop'
b'abcd'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM