简体   繁体   中英

Reading binary data from file in Python and passing it to a C++ function

How to pass binary data loaded by Python directly from a file to a C++ function taking data pointer and size called in a Cython module?

loadFromMemory(const void*, size_t)

This is probably how it would look like in pure Python:

with open('file.bin', 'rb') as f:
    data = f.read()
    loadFromMemory(data, len(data))  # How to do this in Cython?

You need a two step cast first to a char* (which Cython can get easily from a string) and then second to reinterpret that as a void* :

loadFromMemory(<void*>(<char*>data), len(data))

This does assume that loadFromMemory doesn't expect the pointer to remain valid after the function call (Cython won't manage the memory for you automatically, and it'll be freed when data is destroyed).

(Skipping the cast to char* and just casting straight to a void* will take the address of the Python object, which isn't what you want)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM