用户工具

站点工具


linux:python:使用swig连接python与c

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
linux:python:使用swig连接python与c [2026/10/13 22:06] – 外部编辑 127.0.0.1linux:python:使用swig连接python与c [2026/10/13 22:51] (当前版本) – 外部编辑 127.0.0.1
行 9: 行 9:
  
  
-<code python>+ 
 +```python
 from binascii import b2a_hex, a2b_hex from binascii import b2a_hex, a2b_hex
  
行 23: 行 24:
  
 io.py2c_test(a2b,7)   #以c的交互需要使用以byte(a2b)表示的bytes,不能是binascii.b2a_hex之后的。 io.py2c_test(a2b,7)   #以c的交互需要使用以byte(a2b)表示的bytes,不能是binascii.b2a_hex之后的。
-</code>+``` 
  
  
 在swig的.i文件中需要加入以下内容(仅支持python3),表示c char*之间与python bytes相对而不是采用unicode。这一点相当重要,在python中不要使用字符串与C之间传递,而应该用bytes来传递,简单可行,不会发生字符转换规则以及check等等问题(latin-1转换>0x80的字符时有问题,utf8本身也不是属于byte0-255之间的字符定义)。 在swig的.i文件中需要加入以下内容(仅支持python3),表示c char*之间与python bytes相对而不是采用unicode。这一点相当重要,在python中不要使用字符串与C之间传递,而应该用bytes来传递,简单可行,不会发生字符转换规则以及check等等问题(latin-1转换>0x80的字符时有问题,utf8本身也不是属于byte0-255之间的字符定义)。
-<code swig>+ 
 +```swig
  
 %begin %{ %begin %{
 #define SWIG_PYTHON_STRICT_BYTE_CHAR #define SWIG_PYTHON_STRICT_BYTE_CHAR
 %} %}
 +```
  
-</code> 
  
  
 c侧程序示例如下:  注:参数只能写成 char * ,不能写成unsigned char*, 但是可以在c内部通过强制转换将其转换成unsigned char *。 c侧程序示例如下:  注:参数只能写成 char * ,不能写成unsigned char*, 但是可以在c内部通过强制转换将其转换成unsigned char *。
-<code c>+ 
 +```c
 void py2c_test(char * tdi_bytes, int bytes_size) void py2c_test(char * tdi_bytes, int bytes_size)
 { {
行 46: 行 50:
     }     }
 } }
-</code>+``` 
  
  
行 56: 行 61:
 所以C端返回这样的数据需要使用到struct, c端建立以下的struct: 所以C端返回这样的数据需要使用到struct, c端建立以下的struct:
  
-<code c>+ 
 +```c
 typedef struct swig_bytes_data typedef struct swig_bytes_data
 { {
行 62: 行 68:
         char *bytes;         char *bytes;
 } swig_bytes_data; } swig_bytes_data;
 +```
  
-</code> 
  
 c端要返回给python的数据,指定好正确的bytes和size之后,python端即能接收到正常的数据。 c端要返回给python的数据,指定好正确的bytes和size之后,python端即能接收到正常的数据。
行 69: 行 75:
 然后在xxx.i文件中,指定typemap(out) 然后在xxx.i文件中,指定typemap(out)
  
-<code>+ 
 +```
  
 %typemap(out) swig_bytes_data %typemap(out) swig_bytes_data
行 76: 行 83:
         free($1.bytes);         free($1.bytes);
 } }
 +```
  
-</code> 
  
  
行 87: 行 94:
  
 ### - 相关function ### - 相关function
-<code c>+ 
 +```c
 PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len) PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
 //Return value: New reference. //Return value: New reference.
行 105: 行 113:
  
 //If u is NULL, this function behaves like PyUnicode_FromUnicode() with the buffer set to NULL. This usage is deprecated in favor of PyUnicode_New(). //If u is NULL, this function behaves like PyUnicode_FromUnicode() with the buffer set to NULL. This usage is deprecated in favor of PyUnicode_New().
-</code>+``` 
linux/python/使用swig连接python与c.1791900372.txt.gz · 最后更改: 由 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki