Python2与Python3中ctypes.addressof()返回地址差异原因咨询
Hey there, let's clear up the confusion around those drastically different memory addresses you're seeing!
First off: The address difference is not a Python 2 vs 3 issue
What you're observing is actually a standard security feature of modern operating systems called Address Space Layout Randomization (ASLR). Here's the breakdown:
- Every time you launch a process (like your Python interpreter), the OS randomly assigns base memory addresses for the process's code, data, and loaded libraries.
- This means even if you run the exact same code in the same Python version twice, you'll get different memory addresses from
addressof(). The huge gap between your Python 2 and 3 results is just coincidence—two separate process launches with completely random memory layouts.
To test this, try launching Python 3.6 twice in a row and running your code both times: you'll see the address changes each time, just like it would in Python 2 if you restarted it.
Why did you expect addresses to be similar?
It's easy to assume memory addresses would be consistent across runs, but ASLR is designed to make it harder for malicious code to exploit memory vulnerabilities. All modern OSes (Windows, macOS, Linux) enable it by default, so random addresses are the expected behavior.
So why are you getting exceptions in Python 3.6?
The address value itself isn't the problem—ctypes handles large integer addresses just fine in Python 3 (since Python 3's int supports arbitrary sizes, unlike Python 2's separate long type which was still compatible). The real issue is likely something else:
- Check DLL parameter types: Make sure you're passing the buffer to the DLL correctly. In Python 3,
create_string_bufferreturns actypes.c_char_Arrayobject (same as Python 2), but double-check that the DLL expects achar*(byte pointer) and not a wide string pointer (wchar_t*). If your DLL needs Unicode strings, usecreate_unicode_bufferinstead. - Verify pointer casting: If you're manually casting the address to a pointer type, ensure you're using the right ctypes type (e.g.,
ctypes.c_void_p(addressof(p))instead of passing the raw integer directly—though ctypes usually handles this automatically). - DLL architecture compatibility: Confirm the DLL is built for 64-bit (both your Python versions are 64-bit AMD64). A 32-bit DLL would cause conflicts with 64-bit pointer addresses.
Key Takeaway
Don't worry about the absolute value of the memory address—it's supposed to be random. Focus on ensuring you're passing the buffer to the DLL with the correct ctypes types, and that the DLL is compatible with 64-bit Python 3.
内容的提问来源于stack exchange,提问作者loren

