linux:python:使用swig连接python与c
差别
这里会显示出您选择的修订版和当前版本之间的差别。
| 两侧同时换到之前的修订记录前一修订版 | |||
| linux:python:使用swig连接python与c [2026/10/13 22:06] – 外部编辑 127.0.0.1 | linux:python:使用swig连接python与c [2026/10/13 22:51] (当前版本) – 外部编辑 127.0.0.1 | ||
|---|---|---|---|
| 行 9: | 行 9: | ||
| - | < | + | |
| + | ```python | ||
| from binascii import b2a_hex, a2b_hex | from binascii import b2a_hex, a2b_hex | ||
| 行 23: | 行 24: | ||
| io.py2c_test(a2b, | io.py2c_test(a2b, | ||
| - | </ | + | ``` |
| 在swig的.i文件中需要加入以下内容(仅支持python3),表示c char*之间与python bytes相对而不是采用unicode。这一点相当重要,在python中不要使用字符串与C之间传递,而应该用bytes来传递,简单可行,不会发生字符转换规则以及check等等问题(latin-1转换> | 在swig的.i文件中需要加入以下内容(仅支持python3),表示c char*之间与python bytes相对而不是采用unicode。这一点相当重要,在python中不要使用字符串与C之间传递,而应该用bytes来传递,简单可行,不会发生字符转换规则以及check等等问题(latin-1转换> | ||
| - | < | + | |
| + | ```swig | ||
| %begin %{ | %begin %{ | ||
| #define SWIG_PYTHON_STRICT_BYTE_CHAR | #define SWIG_PYTHON_STRICT_BYTE_CHAR | ||
| %} | %} | ||
| + | ``` | ||
| - | </ | ||
| c侧程序示例如下: | c侧程序示例如下: | ||
| - | < | + | |
| + | ```c | ||
| void py2c_test(char * tdi_bytes, int bytes_size) | void py2c_test(char * tdi_bytes, int bytes_size) | ||
| { | { | ||
| 行 46: | 行 50: | ||
| } | } | ||
| } | } | ||
| - | </ | + | ``` |
| 行 56: | 行 61: | ||
| 所以C端返回这样的数据需要使用到struct, | 所以C端返回这样的数据需要使用到struct, | ||
| - | < | + | |
| + | ```c | ||
| typedef struct swig_bytes_data | typedef struct swig_bytes_data | ||
| { | { | ||
| 行 62: | 行 68: | ||
| char *bytes; | char *bytes; | ||
| } swig_bytes_data; | } swig_bytes_data; | ||
| + | ``` | ||
| - | </ | ||
| c端要返回给python的数据,指定好正确的bytes和size之后,python端即能接收到正常的数据。 | c端要返回给python的数据,指定好正确的bytes和size之后,python端即能接收到正常的数据。 | ||
| 行 69: | 行 75: | ||
| 然后在xxx.i文件中,指定typemap(out) | 然后在xxx.i文件中,指定typemap(out) | ||
| - | < | + | |
| + | ``` | ||
| %typemap(out) swig_bytes_data | %typemap(out) swig_bytes_data | ||
| 行 76: | 行 83: | ||
| free($1.bytes); | free($1.bytes); | ||
| } | } | ||
| + | ``` | ||
| - | </ | ||
| 行 87: | 行 94: | ||
| ### - 相关function | ### - 相关function | ||
| - | < | + | |
| + | ```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(). | ||
| - | </ | + | ``` |
linux/python/使用swig连接python与c.1791900372.txt.gz · 最后更改: 由 127.0.0.1
