使用指向struct的C指针作为参数调用Python函数

使用指向struct的C指针作为参数调用Python函数,python,c,pointers,struct,ctypes,Python,C,Pointers,Struct,Ctypes,例如,我使用一组参数调用Python函数 VOID CallPythonFunction( PSOME_COMPLEX_STRUCT Parameter1 , PSOME_COMPLEX_STRUCT Parameter2 , PSOME_COMPLEX_STRUCT Parameter3 , PSOME_COMPLEX_STRUCT Parameter4 ) { PyObject* module_name = PyString_FromStr

例如,我使用一组参数调用Python函数

VOID CallPythonFunction(
      PSOME_COMPLEX_STRUCT Parameter1
    , PSOME_COMPLEX_STRUCT Parameter2
    , PSOME_COMPLEX_STRUCT Parameter3
    , PSOME_COMPLEX_STRUCT Parameter4
    )
{
    PyObject* module_name = PyString_FromString((char*)"plugin");
    PyObject* plugin = PyImport_Import(module_name);
    PyObject* PyTargetFunction = PyObject_GetAttrString(plugin, (char*)"some_function");
    PyObject* args = PyTuple_Pack(4
        , PyLong_FromUnsignedLong((ULONG) Paramater1)
        , PyLong_FromUnsignedLong((ULONG) Paramater2)
        , PyLong_FromUnsignedLong((ULONG) Paramater3)
        , PyLong_FromUnsignedLong((ULONG) Paramater4)
        );
    PyObject* result = PyObject_CallObject(PyTargetFunction, args);
}
例如,这个参数不是标准的C类型,而是指向复杂结构的指针

typedef struct _SOME_COMPLEX_STRUCT 
{
    int field1;
    char field2;
    int  whatever;
} SOME_COMPLEX_STRUCT, *PSOME_COMPLEX_STRUCT;
由于我将其转换为python int对象,因此我不确定如何使用
ctypes
处理此问题,或者是否应该创建python对象

def some_function(parameter1, parameter2, parameter3, parameter4):
    pass
有没有“更好的”/“规范的方法”将此结构作为参数传递

如何修改Python模块中的数据?我正在使用
ctypes

我已经阅读了以下相关问题/答案:


我发现关键是使用
ctypes.cast
,首先以ctypes样式创建复杂结构
ctypes.cast(参数1,ctypes.POINTER(一些复杂的结构))
我明天会测试它。你不应该将指针作为
long
值传递。在64位Windows上,
long
是32位的,因此将截断该值。使用来自voidptr的
PyLong\u
。要使用ctypes访问此文件,请使用
parameter1\u view=SOME\u COMPLEX\u STRUCT.from\u address(parameter1)
。它不拥有
parameter1
所指向的缓冲区,因此您可能希望使用
parameter1=SOME\u COMPLEX\u STRUCT.from\u buffer\u copy(parameter1\u view)
创建一个私有副本。在这种情况下,一些参数是输入/输出缓冲区,以便客户端可以修改de内容。我会试试你的建议,然后写回最后的决议。谢谢<代码>来自地址效率更高。它只需创建该类型的实例并将其
b_ptr
设置为地址
cast
是使用FFI函数调用实现的,这需要做更多的工作。我发现关键是使用
ctypes.cast,首先以ctypes样式创建复杂结构
ctypes.cast(参数1,ctypes.POINTER(一些复杂的结构))
我明天会测试它。你不应该将指针作为
long
值传递。在64位Windows上,
long
是32位的,因此将截断该值。使用来自voidptr的
PyLong\u
。要使用ctypes访问此文件,请使用
parameter1\u view=SOME\u COMPLEX\u STRUCT.from\u address(parameter1)
。它不拥有
parameter1
所指向的缓冲区,因此您可能希望使用
parameter1=SOME\u COMPLEX\u STRUCT.from\u buffer\u copy(parameter1\u view)
创建一个私有副本。在这种情况下,一些参数是输入/输出缓冲区,以便客户端可以修改de内容。我会试试你的建议,然后写回最后的决议。谢谢<代码>来自地址
效率更高。它只需创建该类型的实例并将其
b_ptr
设置为地址
cast
是使用FFI函数调用实现的,这需要做更多的工作。