【问题标题】:How do I marshal a pointer to a cstring between Python and C via SWIG如何通过 SWIG 在 Python 和 C 之间编组指向 cstring 的指针
【发布时间】:2014-03-14 17:25:04
【问题描述】:

我不知道如何在 python 和 C 之间编组指向 c 字符串的指针。我正在尝试使用签名包装现有库:

int connect(char* url, char** host, char** port, char** path);

其中主机、端口和路径由连接函数设置。 url 参数很好,但是双指针导致了麻烦。

我需要在我的 .i 文件中放入什么才能使双指针正确编组?

【问题讨论】:

    标签: python c swig


    【解决方案1】:

    如果char** 参数仅用于输出,则以下将起作用。由于未指定实现,我将 malloc 返回的参数并假定为 ASCII/UTF-8 字符串。我还将假设 Python 3。

    %module x
    
    %{
    #include <stdlib.h>
    #include <stdio.h>
    %}
    
    %include <exception.i>
    
    // This makes char** output-only and it won't be a required parameter in the
    // Python interface.  A temporary char* is created for each char** encountered
    // and its address is used for the char** parameter.
    %typemap(in,numinputs=0) char** (char* tmp) %{
        $1 = &tmp;
    %}
    
    // This typemap is processed after calling the function.
    // It converts the returned value to a Python Unicode string.
    // The malloc'ed return value is no longer needed so is freed.
    %typemap(argout) char** (PyObject* tmp) %{
        tmp = PyUnicode_FromString(*$1);
        $result = SWIG_Python_AppendOutput($result,tmp);
        free(*$1);
    %}
    
    %inline %{
    int connect(char* url, char** host, char** port, char** path)
    {
        *host = malloc(10);
        *port = malloc(10);
        *path = malloc(10);
        strcpy(*host,"host");
        strcpy(*port,"port");
        strcpy(*path,"path");
        return 1;
    }
    %}
    

    演示:

    >>> import x
    >>> x.connect('url')
    [1, 'host', 'port', 'path']
    

    【讨论】:

    • 谢谢。稍后我将尝试此操作,并在验证后标记为正确。干杯!
    • 完美运行。我有一些这样的东西,但我错过了它们现在成为退货清单的一部分。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多