문제

I can't figure out how to marshal a pointer to a c-string between python and C. I'm trying to wrap and existing library with the signature:

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

Where host, port, and path are set by the connect function. The url param is fine, but the double-pointers are causing the trouble.

What do I need to put in my .i file to get the double-pointers to marshal properly?

도움이 되었습니까?

해결책

If the char** parameters are output-only, the following will work. Since the implementation is not specified I'll malloc the returned parameters and assume ASCII/UTF-8 strings. I'll also assume 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;
}
%}

Demo:

>>> import x
>>> x.connect('url')
[1, 'host', 'port', 'path']
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top