+-
Python ctypes设置c_char_p基础值
我有一个指向结构的指针.在该结构内部,字段之一是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进程无法获得反映的更改.

我如何“管理”栏,以便对其进行设置,并且更改会在任何其他具有指向相同地址的指针的应用程序中反映出来?

最佳答案
根据注释,您有一个返回POINTER(foo)实例的函数.这是一个读取返回值并对其进行更改的工作示例.如果您的代码仍无法正常工作,请创建一个类似的示例来重现该问题:

测试

#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'
点击查看更多相关文章

转载注明原文:Python ctypes设置c_char_p基础值 - 乐贴网