简体   繁体   中英

How to pass '\x00' from python to c function?

python:

msg = b'aaa\x01' + b'\x00' + b'\x23\x45cc'
dl = cdll.LoadLibrary
lib = dl("./test.so")
lib.send.argtypes = c_char_p
lib.send(msg)

c (test.so):

void send(char * msg)
{       
        // printf("%s", msg);
        SSL_write(ssl, msg, strlen(msg));
}

how can I pass '\x00' and what's behind it in?

Thanks!

As indicated in comments, printf with %s only prints a char* up to the first null byte found. The C function needs to know the size and some of your bytes are non-printing characters, so printing the bytes in hexadecimal for the specified length is an option:

test.c

#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API void send(const char* msg, size_t size)
{
    for(size_t i = 0; i < size; ++i)
        printf("%02X ", msg[i]);
    printf("\n");
}

test.py

import ctypes as ct

msg = b'aaa\x01\x00\x23\x45cc'
dll = ct.CDLL('./test')
dll.send.argtypes = ct.c_char_p, ct.c_size_t
dll.send.restype = None
dll.send(msg, len(msg))

Output:

61 61 61 01 00 23 45 63 63

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