python swig char*类型返回

16 篇文章 0 订阅

%cstring_output_allocate does work with multiple parameters. It declares "If you see char **output as a parameter to any method, hide the parameter and return it as an additional output.

Here's an example. I declare two methods: one that returns a value and one that doesn't. Note in the output how the output parameter is not passed, but it's result is returned as an additional return value.

Example

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);
}
x.h

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

%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']
原文链接:https://stackoverflow.com/questions/10061053/passing-multiple-parameters-and-allocating-strings-in-c-using-swig-python
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值