簡體   English   中英

使用 Swig/Python 在 C 中傳遞多個參數並分配字符串

[英]Passing multiple parameters and allocating strings in C using Swig/Python

我正在使用 SWIG 包裝以下 C 接口以從 Python 訪問它:

void some_method(char **output, int paramA, const char *paramB, int paramC);

C 中的實現在運行時使用 malloc() 將 memory 分配給指針 *output。 其他參數是只讀的,並傳達該方法所需的附加信息。

對應的 SWIG 接口文件應該是什么樣的?

如果我只傳遞在 C 中動態分配的“輸出”參數,而不傳遞其他參數,這種情況就非常簡單。 即如果我的 C 接口如下,它的實現是 example.c(比如說):

void some_method(char **output);

然后 SWIG 接口文件很簡單,如本 stackoverflow 線程中所述:

%module example
%include<cstring.i>
%cstring_output_allocate(char **output, free(*$1));
%{  
    extern void some_method(char **output);
%}
%include example.c

以上不適用於多個參數。 如何傳遞多個參數,以及允許動態分配其中一個參數(在本例中為“輸出”參數)。

%cstring_output_allocate確實可以使用多個參數。 它聲明“如果您看到char **output作為任何方法的參數,請隱藏該參數並將其作為附加 output 返回。

這是一個例子。 我聲明了兩種方法:一種返回值,另一種不返回值。 請注意在 output 中如何不傳遞output參數,但它的結果作為附加返回值返回。

例子

x.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void some_method(char **output, int paramA, const char *paramB, int paramC)
{
    *output = malloc(paramA);
    sprintf_s(*output,paramA,"%s_%d",paramB,paramC);
}

int some_method2(char **output, int paramA, const char *paramB, int paramC)
{
    *output = malloc(paramA);
    sprintf_s(*output,paramA,"%s_%d",paramB,paramC);
    return strlen(*output);
}

xh

void some_method(char **output, int paramA, const char *paramB, int paramC);
int some_method2(char **output, int paramA, const char *paramB, int paramC);

%module x

%begin %{
#pragma warning(disable:4100 4127 4211 4706)
%}

%{
#include "x.h"
%}

%include<cstring.i>
%cstring_output_allocate(char **output, free(*$1));
%include "x.h"

makefile

_x.pyd: x.c x_wrap.c x.h
    cl /LD /W4 /MD /Ic:\python27\include x.c x_wrap.c -link /LIBPATH:c:\python27\libs

x_wrap.c: x.i x.h
    swig -python x.i

Output

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import x
>>> x.some_method(100,'blah',123)
'blah_123'
>>> x.some_method2(100,'blah',123)
[8, 'blah_123']

不是直接的答案,但您正在處理的內容聽起來足夠低級,您可能需要考慮放棄 SWIG 並直接使用CPython api SWIG 很棒,但它增加了另一個依賴項和生成的代碼負載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM