Python is passing 32bit pointer address to C functions -
i call c functions within shared library python scripts. problem arrises when passing pointers, 64bit addresses seem truncated 32bit addresses within called function. both python , library 64bit.
the example codes below demonstrate problem. python script prints address of data being passed c function. then, address received printed within called c function. additionally, c function proves 64bit printing size , address of locally creating memory. if pointer used in other way, result segfault.
cmakelists.txt
cmake_minimum_required (version 2.6) add_library(plate module plate.c)
plate.c
#include <stdio.h> #include <stdlib.h> void plate(float *in, float *out, int cnt) { void *ptr = malloc(1024); fprintf(stderr, "passed address: %p\n", in); fprintf(stderr, "local pointer size: %lu\n local pointer address: %p\n", sizeof(void *), ptr); free(ptr); }
test_plate.py
import numpy import scipy import ctypes n = 3 x = numpy.ones(n, dtype=numpy.float32) y = numpy.ones(n, dtype=numpy.float32) plate = ctypes.cdll.loadlibrary('libplate.so') print 'passing address: %0x' % x.ctypes.data plate.plate(x.ctypes.data, y.ctypes.data, ctypes.c_int(n))
output python-2.7
in [1]: run ../test_plate.py
passing address: 7f9a09b02320
passed address: 0x9b02320
local pointer size: 8
local pointer address: 0x7f9a0949a400
the problem ctypes
module doesn't check function signature of function you're trying call. instead, bases c types on python types, line...
plate.plate(x.ctypes.data, y.ctypes.data, ctypes.c_int(n))
...is passing the first 2 params integers. see eryksun's answer reason why they're being truncated 32 bits.
to avoid truncation, you'll need tell ctypes
params pointers like...
plate.plate(ctypes.c_void_p(x.ctypes.data), ctypes.c_void_p(y.ctypes.data), ctypes.c_int(n))
...although they're pointers to matter - may not pointers float
c code assumes.
update
eryksun has since posted more complete answer numpy
-specific example in question, i'll leave here, since might useful in general case of pointer truncation programmers using other numpy
.
Comments
Post a Comment