上面已经说了,string的传入传出。
那么。当我们二进制输入输出怎么做呢?
根据官方说明:http://www.swig.org/Doc3.0/Python.html#Python_nn77
In some cases, users may wish to instead handle all byte strings as bytes objects in Python 3. This can be accomplished by adding SWIG_PYTHON_STRICT_BYTE_CHAR to the generated code:
%module char_to_bytes %begin %{ #define SWIG_PYTHON_STRICT_BYTE_CHAR %} char *charstring(char *s) { return s; }This will modify the behavior so that only Python 3 bytes objects will be accepted and converted to a C/C++ string, and any string returned from C/C++ will be converted to a bytes object in Python 3:
>>> from char_to_bytes import * >>> charstring(b"hi") # Byte string b'hi' >>> charstring("hi") # Unicode string Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: in method 'charstring', argument 1 of type 'char *'
我们修改文件:
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;
}
char * get_str_inputbytes(char * str1,int len)
{
char * odata=(char *)malloc(100);
sprintf(odata,"%s:%s","Header",str1);
return odata;
}
<--
i-->
%module tsm
%apply (char *STRING, int LENGTH) { (char * str1,int len) };
%header%{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
%{
//头文件
extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
extern char * get_str_inputbytes(char * str1,int len);
%}
%newobject get_str_addheader;
extern char * get_str(const char * str1);
extern char * get_str_addheader(char * str1);
extern char * get_str_inputbytes(char * str1,int len);
<--
编译之后进行测试:
当加入
%header%{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
输入变为byte,可以进行二进制处理。
但是,还是会遇到00会有结束。我们需要继续查看文档。。,处理呕吐打他