11

I've made a little test program in python to test some C functions in many cases. This python program use ctypes to import and use my C functions.

But I'd also like to test minimum and maximum values cases (limits.h's ULLONG_MAX for instance).

But since some of these limits can be system dependant, I'd prefer to avoid hard coding it in my program; I'd rather dynamically get it.

Is it possible to get these limits values in python?

Liran Funaro
  • 2,750
  • 2
  • 22
  • 33
vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • Possible duplicate of [How can I reference #defines in a C file from python?](https://stackoverflow.com/questions/12147394/how-can-i-reference-defines-in-a-c-file-from-python) – nitzanms Jun 21 '17 at 14:25
  • Might worth reading: [\[SO\]: Maximum and minimum value of C types integers from Python (@CristiFati's answer)](https://stackoverflow.com/a/52485502/4788546). – CristiFati Jul 06 '22 at 12:00

1 Answers1

6

I believe the closest you can get is

ctypes.sizeof(whatever_type)

which gives you the size of the type in bytes. For example, you can use ctypes.sizeof(ctypes.c_int) to figure out whether a byte is 4 bytes, 8, or some other weird number.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    Or assume 2's complement and use a negative -1 value with the corresponding unsigned type, e.g. `c_uint(-1).value` for the unsigned limit, and divide the unsigned max by 2 to get the signed max. – Eryk Sun May 22 '17 at 23:08
  • @eryksun: All I've found in the docs about passing an out-of-range value is that "no overflow checking is done", so I don't know whether `c_uint(-1)` is actually supported. – user2357112 May 22 '17 at 23:11
  • 1
    No overflow checking means that it does overflow without raising an exception. That's what I'm depending on, and know from the source, but you're right that the docs are poorly worded. – Eryk Sun May 22 '17 at 23:14
  • 1
    @user2357112 Your solutions sounds really elegant! @eryksun's solution works on my system. To get signed types limit values, a little trick is enough, for instance : `ctypes.c_uint(-1).value // 2` for `INT_MAX` and `(-ctypes.c_uint(-1).value) // 2` for `INT_MIN` – vmonteco May 22 '17 at 23:24
  • 2
    @vmonteco, it'll work on any system supported by CPython. Setting the value of simple integer ctypes is implemented via `PyLong_AsUnsignedLong[Long]Mask` with a subsequent cast to the target C type. But the docs are less than clear. – Eryk Sun May 22 '17 at 23:30
  • @vmonteco - Thank you for the comment above. May I ask why -1 must be used to determine these values? My brief tests show that no other number can be used to determine the TYPE_MIN / TYPE_MAX values. (I'm using bit shifting myself - but this seems more straight-forward.) – S3DEV Apr 02 '22 at 09:52