How can I print the contents of an address after sending the pointer to a c++ dll from Python?

33 Views Asked by At

//The function in the dll is where all I am doing is writing a value to that address:

BOOL test_sizeKey(unsigned short *sizeKey)
{
    BOOL rc = TRUE;
    *sizeKey = 150;
    return rc;
}

My python program that loads the dll is as follows.:

import ctypes

my_dll = ctypes.WinDLL("C:/CFiles/test_dll/SimpleArg/x64/Debug/SimpleArg.dll")

USHORT = ctypes.c_ushort

func6 = my_dll.test_sizeKey
sizeKey = USHORT()
sizeKey = ctypes.byref(sizeKey)

func6.argtypes = [
    ctypes.POINTER(USHORT)                  # sizeKey (pointer to USHORT)
]
func6.restype = ctypes.c_bool

success6 = func6(
    sizeKey
)
print(sizeKey)

The output I am getting when I print the last variable is:

<cparam 'P' (0x0000020403CF8498)>
1

There are 1 best solutions below

0
Mark Tolonen On
import ctypes as ct
import ctypes.wintypes as w  # for BOOL and USHORT

# WinDLL is for __stdcall calling convention.
# Won't matter on 64-bit as __stdcall and __cdecl are the same,
# but matters on 32-bit OSes.  Use the correct one for portability.
dll = ct.CDLL("C:/CFiles/test_dll/SimpleArg/x64/Debug/SimpleArg.dll")
test_sizeKey = dll.test_sizeKey
test_sizeKey.argtypes = ct.POINTER(ct.c_ushort),
test_sizeKey.restype = w.BOOL  # BOOL is typically "typedef int BOOL;".  c_bool is byte-sized.

sizeKey = ct.c_ushort()  # instance of C unsigned short
result = test_sizeKey(ct.byref(sizeKey))  # pass by reference
print(sizeKey.value)  # read the value