0
Python and unsigned int
Hi I understand python does bit have data types strictly but I am in need of unsigned int Let me brief you about the story. I have a c++ api which takes unsigned int as an argument and updates that value. I have swig binding generated for this api which I will use into python. Now, as we have option of below: obj = myclass() Makes obj as myclass instance, how to do it for unsigned int Basically I want to declare a variable of unsigned int and laaa that variable to my api which will update value of unsigned int. Basically, I need a mechanism in python to generate unsigned int object
3 odpowiedzi
+ 4
Though I am unfamiliar with using SWIG, I explored your question with ChatGPT. The primary answer was that it should work as long as you don't try to pass a negative integer.
Taking it further, I asked how to make SWIG cast a negative int as unsigned. It gave me the SWIG setup below. I hope this helps:
%module example
%{
#include "example.h"
%}
// Custom typemap to convert negative Python integers to their unsigned representation
%typemap(in) unsigned int {
long temp = PyLong_AsLong($input);
if (PyErr_Occurred()) return NULL; // Handle conversion errors
$1 = static_cast<unsigned int>(temp); // Proper bitwise conversion
}
%include "example.h"
+ 4
have you tried ctypes?
import ctypes
u32_1 = ctypes.c_uint32(-1).value
print(u32_1)
u8_1 = ctypes.c_uint8(0).value
print(u8_1)
u8_2 = ctypes.c_uint8(-1).value
print(u8_2)
https://docs.python.org/3/library/ctypes.html
+ 4
Ketan Lalcheta
perhaps go over the swig documentaion once again. specifially in the typemap section. Brian's example uses this.
31.8.1 What is a typemap?
https://www.swig.org/Doc1.3/JUMP_LINK__&&__Python__&&__JUMP_LINK.html#Python_nn2
also, why choose Swig and not Cython? Swig is harder to work with because it's designed for multiple languages. Cython is for Python specifically.