如何在CFFI中找到指向结构的指针的地址并将其强制转换为void**

How to find address of a pointer to structure and cast it to void** in CFFI

本文关键字:转换 void 地址 指针 CFFI 结构      更新时间:2023-10-16

我在C++中的代码是

StructureEx* obj; // structure
functionEx((void**)&obj);

我的功能是

int functionEx(void** obj); //calling function

我是CFFI的新手。所以我的问题是

  1. 我如何在CFFI中实现同样的目标?

  2. 如何在CFFI中找到指针的地址、指向结构的指针?

我知道铸造到void**可以通过完成

ffi.cast("void*",address)

但是我怎样才能得到那个地址并传递给函数呢?

可以声明可能可用的arg = ffi.new("void **")

以下代码打印

<cdata'void*'NULL>

<cdata'void*'0xc173c0>

7

即首先指针的值为零,并且在调用之后该值对应于functionEx中设置的值。

from cffi import FFI
ffi = FFI()
ffi.cdef("""int functionEx(void** obj);""")
C = ffi.dlopen("./foo.so")
print(C)
arg = ffi.new("void **")
print(arg[0])
C.functionEx(arg)
print(arg[0])
ints = ffi.cast("int *", arg[0])
print(ints[7])
#include <stdio.h>
#include <stdlib.h>
int functionEx(void ** obj)
{
    int * arr;
    int i;
    *obj = malloc(sizeof(int) * 8);
    arr = *obj;
    for (i=0; i<8; i++) {
        arr[i] = i;
    }
    return 0;
}