python ctypes C++ 取回 char* 在 linux 上缺少最后一个字符

标签 python c++ linux ctypes

我有以下 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;
}

它使用 ifreq 获取本地 PC 的 mac 地址并将其粘贴到一个字符数组中。 该例程在“Utility.so”中编译

然后我有以下 python 代码:

from ctypes import *
mydll=cdll.LoadLibrary("./Utility.so")
mac_string = c_char_p(mydll.get_mac()).value
print mac_string

我得到以下结果 02:00:AC:99:00:9

当我的 MAC 实际上是:02:00:AC:99:00:9C

所以我错过了最后一个字符。

有什么想法吗?

注意:它在 Mac 和 Windows 上都能正常工作!

请帮助.- 问候。 cp

最佳答案

在 C/C++ 中,c 字符串以 NULL 结尾,这意味着结尾由 NULL(字节 0)标记。

要存储 17 个字符的文本(MAC 的长度),您的数组需要 18 个字符,以说明最后的 NULL。

snprintf ( http://www.cplusplus.com/reference/cstdio/snprintf/ ) 将确保它可以写入 NULL,因此它只写入 MAC 的 16 个字节,然后是尾随的 NULL。

简而言之:

size_t byteToAlloc = 18;

关于python ctypes C++ 取回 char* 在 linux 上缺少最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43683939/

相关文章:

c++ - vector 超出范围而不给出错误

c++ - 如何打印 std::set of std::maps

linux - R,如何在带有时区和垃圾 Unicode 字符的 Linux 上使用 strptime

Python:同时使用 os.fork()、os.pipe() 和 subprocess.Popen 问题

python - 在生成器中使用 with 语句是否明智?

c++ - C++ 中 BigInt 类的良好和基本实现

linux - 如何解码 H323 数据包?

PHP GD - 不同的文本偏移 Mac 与 Linux

python - 使用 Pyinstaller 时找不到隐藏的导入 Tensorflow 包

python - PySpark 在映射 lambda 中序列化 'self' 引用对象?