在Python中实现char const*const names[]的最佳方法是什么

2024-04-26 13:14:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将“char const*const names[]”参数传递给C API。如何在python ctypes中获得指向常量字符的常量指针?在

我试着用 string1=“先打招呼” 名称=ctypes.c_wchar_p(字符串1)

来自C的Api调用将是: char const*const names[]={“AVeryLongName”,“Name”}


Tags: 字符串名称apinamesctypes字符指向常量
2条回答

你应该先看看[Python 3]: ctypes - A foreign function library for Python。一些想法:

  • 您不能通过ctypes指定constness(或者至少,我不知道如何)。一个关于赢的小例子:

    >>> from ctypes import wintypes
    >>> wintypes.LPCSTR == wintypes.LPSTR
    True
    

    因此,数组的ctypes包装器与char *names[] = ....

  • Python3开始,(8bit)char序列(ctypes.c_char_p)不再是str对象,而是[Python 3]: Bytes。{5>当你有一个普通的}前缀时,你可以声明一个{普通}字符串:

    >>> s = "Some string"
    >>> type(s)
    <class 'str'>
    >>> b = b"Some string"
    >>> type(b)
    <class 'bytes'>
    

    注意:要将常规字符串转换为字节,请使用[Python 3]: str.encode(encoding="utf-8", errors="strict"):"Dummy string".encode()

  • 无法从Python执行未大小(char*)数组;有两种解决方法:

    1. 声明有大小的数组
    2. 声明一个指针(类型:ctypes.POINTER(ctypes.c_char_p)


    让我们看一下1的一个简短示例。

    >>> ARRAY_DIM = 2
    >>> CharPArr = ctypes.c_char_p * ARRAY_DIM
    >>> CharPArr
    <class '__main__.c_char_p_Array_2'>
    >>> names = CharPArr(b"AVeryLongName", "Name".encode())
    >>> names, names[0], names[1]
    (<__main__.c_char_p_Array_2 object at 0x000002E6DC22A3C8>, b'AVeryLongName', b'Name')
    

    上面的names对象可以传递给接受char const *const names[]的函数,尽管我不确定该函数如何确定数组的长度(除非另一个参数保持其长度)。在

    Python 2的eem>也是如此:

    >>> ARRAY_DIM = 2
    >>> CharPArr = ctypes.c_char_p * ARRAY_DIM
    >>> CharPArr
    <class '__main__.c_char_p_Array_2'>
    >>> names = CharPArr("AVeryLongName", "Name")
    >>> names, names[0], names[1]
    (<__main__.c_char_p_Array_2 object at 0x7f39bc03c5f0>, 'AVeryLongName', 'Name')
    

@EDIT0

添加了Python 2的变体

这就是我最终实现的方式,它似乎与Python2.7一起工作。在

示例C文件:

void sam_test(char const *const names[],int n)
{
 int i;
   for (i = 0; i < n; i++) {
     printf ("%s \n", (names[i]));
   }
}

Python:

^{pr2}$

相关问题 更多 >