您的位置:首页 > 编程语言 > Python开发

SWIG Python-C封装 char*相关问题(1)

2017-08-23 00:00 176 查看
相关资料SWIG-Python:http://www.swig.org/Doc3.0/Python.html

返回类型相关资料:http://www.swig.org/Doc3.0/Python.html#Python_nn22

SWIG里面对于char *的使用严格限制,防止内存泄露,毕竟这个东西没有任何的验证机制,但是对于封装C/C++包装,指针类型的是不可缺少的东西。

不说理论了,直接从事件做起。

example 1:处理string相关的问题初体验

c  -->

#include "string.h"

char * get_str(char * str1)
{
return str1;
}

<--

i -->

%module tsm

%{
//头文件
extern char * get_str(const char * str1);

%}

extern char * get_str(const char * str1);

<--




根据测试函数只会接受string类型,bytes类型不接受。所以目前的配置只适合写string相关的函数。

根据以上结论,把函数写的复杂些

example2 :扩展string处理

c -->
#include "string.h"
#include <stdlib.h>
#include <stdio.h>

char * get_str(char * str1)
{
return str1;
}
char * get_str_addheader(char * str1)
{
char * odata=(char *)malloc(100);
sprintf(odata,"%s:%s","Header",str1);
return odata;
}
<--

i -->
%module tsm

%{
//头文件
extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
%}

extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
<--




输入为string类型时候,可见,可以完美运行。

不过根据官方文档说明:

9.3.3 Using %newobject to release memory

If you have a function that allocates memory like this,

char *foo() {
char *result = (char *) malloc(...);
...
return result;
}
then the SWIG generated wrappers will have a memory leak--the returned data will be copied into a string object and the old contents ignored.

To fix the memory leak, use the %newobject directive.

所以我们需要在interface文件中修改为

...
if (alloc1 == SWIG_NEWOBJ) free((char*)buf1);
free((char*)result);
...

i -->
%module tsm

%{
//头文件
extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
%}
%newobject get_str_addheader;
extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
<--
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Cwrap python