[英]python ctypes C++ get back char* missing last character on linux
i have the following C++ code: 我有以下C ++代码:
__declspec(dllimport) char* get_mac()
{
size_t byteToAlloc = 17;
char *mac_addr = (char*) malloc(byteToAlloc);
struct ifreq buffer;
int s = socket(PF_INET, SOCK_DGRAM, 0);
strcpy(buffer.ifr_name,"enp0s3");
if (0 == ioctl(s, SIOCGIFHWADDR, &buffer))
{
// Save Mac Address in hex format
snprintf(mac_addr, byteToAlloc, "%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char) buffer.ifr_hwaddr.sa_data[0],
(unsigned char) buffer.ifr_hwaddr.sa_data[1],
(unsigned char) buffer.ifr_hwaddr.sa_data[2],
(unsigned char) buffer.ifr_hwaddr.sa_data[3],
(unsigned char) buffer.ifr_hwaddr.sa_data[4],
(unsigned char) buffer.ifr_hwaddr.sa_data[5]);
}
close(s);
return mac_addr;
}
which is using ifreq to get the mac address of the local PC and sticks it into a array of chars. 使用ifreq来获取本地PC的mac地址,并将其粘贴到一个字符数组中。 The routine gets compiled in the "Utility.so"
该例程在“ Utility.so”中编译
Then i have the following python code: 然后我有以下python代码:
from ctypes import *
mydll=cdll.LoadLibrary("./Utility.so")
mac_string = c_char_p(mydll.get_mac()).value
print mac_string
and i get the following result 02:00:AC:99:00:9 我得到以下结果02:00:AC:99:00:9
when my MAC is actually: 02:00:AC:99:00:9C 我的MAC实际上是:02:00:AC:99:00:9C
So im' missing the last char. 所以我错过了最后一个字符。
any idea ? 任何想法 ?
NOTE: it works fine on both Mac and Windows ! 注意:在Mac和Windows上都可以正常工作!
please help.- greetings. 请帮助。-问候。 cp
cp
In C/C++, c-strings are NULL-terminated, which means the end is marked by a NULL (byte 0). 在C / C ++中,c字符串以NULL终止,这意味着结尾用NULL(字节0)标记。
To store 17 chars of text (the length of the MAC), your array needs to be 18 characters, to account for that final NULL. 要存储17个字符的文本(MAC的长度),您的数组必须为18个字符,以说明该最终NULL。
snprintf ( http://www.cplusplus.com/reference/cstdio/snprintf/ ) will make sure it can write a NULL, so it is only writing 16 bytes of the MAC, and then the trailing NULL. snprintf( http://www.cplusplus.com/reference/cstdio/snprintf/ )将确保它可以写入NULL,因此它仅写入16个字节的MAC,然后写入尾随的NULL。
In short: 简而言之:
size_t byteToAlloc = 18;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.