gpt4 book ai didi

Cython:将指针传递给函数中的指针,采用 void **

转载 作者:行者123 更新时间:2023-11-30 16:22:49 30 4
gpt4 key购买 nike

我正在尝试编写一个函数,在某些条件下,将指向结构的指针更改为指向不同的结构。

我的限制是我想保留初始函数签名,该签名将指向指针(而不是特定结构类型)的通用指针作为参数。

这行不通:

[nav] In [5]: %%cython -f 
...: ctypedef struct A:
...: int x
...: int y
...:
...: cdef fn(void **m):
...: # Arbitrary code that changes m[0] to point to another structure
...: pass
...:
...: cdef A a
...: cdef A *ap = &a
...: a.x = 2
...: a.y = 3
...: print(ap.x)
...: fn(&ap)
...: print(ap.x)

Error compiling Cython file:
------------------------------------------------------------
...
cdef A a
cdef A *ap = &a
a.x = 2
a.y = 3
print(a.x)
fn(&ap)
^
------------------------------------------------------------

/home/me/.cache/ipython/cython/_cython_magic_3c3902694eafae18c66cb761d4a6b210.pyx:20:3: Cannot assign type 'A **' to 'void **'

我猜这是因为即使我可以编写一个以 void * 作为参数的函数,并自动将任何传递的指针转换为 void *,这也会获胜不能使用指向 void 指针的指针,对吗?

如果是这样,我如何传递结构指针,以便 ap 可以指向不同的结构?

谢谢。

编辑:

进一步阅读后,我意识到这是一个 C 架构“功能”。 This useful article给出一些简短的解释:

One side point about pointers to pointers and memory allocation: although the void * type, as returned by malloc, is a "generic pointer", suitable for assigning to or from pointers of any type, the hypothetical type void ** is not a "generic pointer to pointer." Our allocstr example can only be used for allocating pointers to char. It would not be possible to use a function which returned generic pointers indirectly via a void ** pointer, because when you tried to use it, for example by declaring and calling

double *dptr;
if(!hypotheticalwrapperfunc(100, sizeof(double), &dptr))
fprintf(stderr, "out of memory\n");

you would not be passing a void **, but rather a double **.

我认为此时我能做的就是在函数签名中指定数据类型,或者返回新分配的值?

最佳答案

我通过传递函数所要求的内容来解决这个问题,即 void **,然后在需要时进行转换:

[nav] In [5]: %%cython -f 
...: ctypedef struct A:
...: int x
...: int y
...:
...: cdef fn(void **m):
...: # Arbitrary code that changes m[0] to point to another structure
...: pass
...:
...: cdef A a
...: cdef void *avp = <void *>&a
...: cdef A *ap = <A*>avp
...: a.x = 2
...: a.y = 3
...: print(ap.x)
...: fn(&ap)
...: ap = <A*>avp # Must reassign
...: print(ap.x)

关于Cython:将指针传递给函数中的指针,采用 void **,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274362/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com