1

I want to transform a python integer to a boost multi precision cpp_int in C++, to be able to work with integers of arbitrary size. My code is entirely in C++, so I need to do this using Python API for C, working with PyObject.

I am currently doing it through string representation using PyObject_Str and PyUnicode_AsUTF8AndSize. Is it possible to optimize this by using byte array instead? boost cpp_int has import_bits to generate from a byte array, but I couldn't find anything in python C api to transform an integer to bytes (like to_bytes in python) PyObject_Bytes and PyBytes_FromObject don't seem to work. both return NULL.

Vlad Keel
  • 372
  • 2
  • 13
  • _"My code is entirely in C++, so I need to do this using Python API for C, working with PyObject"_ - this seems conflicting information. "My code is entirely in C++" - so no relation to python then. "So I need to do this using Python API for C" - what happened to C++ again? Can you state exactly what the goal is (e.g. how do you end up with the python value in the first place?), without unnecessary claims. Also, consider showing the code you already have. – sehe Nov 30 '22 at 03:34
  • Sure. My code is in C++. C++ is compatible with C so I'm able to use Python C API https://docs.python.org/3.7/c-api/index.html I get the python value from a user, who writes Python code that import my module. – Vlad Keel Nov 30 '22 at 06:34
  • 1
    If something's returning `NULL` then you need to call `PyErr_Print()` to see what's gone wrong. However, you can call Python functions from the Python C API (https://docs.python.org/3/c-api/call.html#object-calling-api) - not everything has a dedicated C API function. So maybe just use that to call `int.to_bytes` – DavidW Nov 30 '22 at 18:48

0 Answers0