4

Is there a way to get a pointer to an element in the middle of an ctypes array? Example:

lib = ctypes.cdll.LoadLibrary('./lib.so')
arr = (ctypes.c_int32 * 100)()
lib.foo(arr)

Now I don't want to call foo with a pointer to the first element of arr, but on the 10th. That would be equivalent to C notation &arr[9]:

lib.foo(&arr[9])

Is there a smart way to do this?

3
  • How does the (C) foo function declaration looks like? Commented Jul 9, 2018 at 13:12
  • In this example it could be void foo(int32_t *arr) Commented Jul 9, 2018 at 14:41
  • Ok, and inside the func, I imagine there's some processing taking place. That processing involves accessing the elements of the array (passed as a pointer). ?How does the function when to stop? meaning that If i pass a 100 values array how does it know not to access 101th element? Commented Jul 9, 2018 at 14:54

1 Answer 1

6

byref has an optional parameter to add a byte offset to the address.

test.dll (Windows)

__declspec(dllexport) int foo(int* arr)
{
    return *arr;
}

Example:

>>> from ctypes import *
>>> lib = CDLL('test')
>>> arr = (c_int * 100)(*range(100))
>>> arr[9]
9
>>> lib.foo(arr)
0
>>> lib.foo(byref(arr,sizeof(c_int) * 9))
9
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.