【发布时间】:2014-03-14 17:25:04
【问题描述】:
我不知道如何在 python 和 C 之间编组指向 c 字符串的指针。我正在尝试使用签名包装现有库:
int connect(char* url, char** host, char** port, char** path);
其中主机、端口和路径由连接函数设置。 url 参数很好,但是双指针导致了麻烦。
我需要在我的 .i 文件中放入什么才能使双指针正确编组?
【问题讨论】:
我不知道如何在 python 和 C 之间编组指向 c 字符串的指针。我正在尝试使用签名包装现有库:
int connect(char* url, char** host, char** port, char** path);
其中主机、端口和路径由连接函数设置。 url 参数很好,但是双指针导致了麻烦。
我需要在我的 .i 文件中放入什么才能使双指针正确编组?
【问题讨论】:
如果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']
【讨论】: