Ash
Ash

Reputation: 949

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

My code in C++ is

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

and my function is

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

I am new to CFFI. So my question is

  1. How can I achieve the same in CFFI?

  2. How to find the address of a pointer, pointer to structure in CFFI?

I know casting to void** can be done by

ffi.cast("void*",address)

But how can I get that address and pass to the function?

Upvotes: 3

Views: 1825

Answers (1)

J.J. Hakala
J.J. Hakala

Reputation: 6214

It is possible to declare arg = ffi.new("void **") that may be usable.

The following code prints

<cdata 'void *' NULL>

<cdata 'void *' 0xc173c0>

7

i.e. first the value of pointer is zero, and after the call the value corresponds to the value set in 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;
}

Upvotes: 3

Related Questions