Created
October 13, 2012 02:23
-
-
Save xieran1988/3882963 to your computer and use it in GitHub Desktop.
Python Common
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Python: 从 C 调用 Python | |
// | |
#include <Python.h> | |
// 有长度的字符串 | |
PyObject *r = PyObject_CallFunction(func, "s#", "str", 3); | |
// 以0结尾的字符串 | |
PyObject *r = PyObject_CallFunction(func, "s", "str with NUL terminate"); | |
// 无符号整形 unsigned long | |
PyObject *r = PyObject_CallFunction(func, "k", 1988UL); | |
// 有符号整形 int | |
PyObject *r = PyObject_CallFunction(func, "i", -23); | |
// 更多类型信息请见 http://docs.python.org/c-api/arg.html | |
// 调用完之后使用 PyErr_Print() 可以打印出错信息 | |
PyObject_CallFunction(...); | |
PyErr_Print(); | |
/* | |
输出: | |
Traceback (most recent call last): | |
File "./conn.py", line 121, in <module> | |
raise | |
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType | |
*/ | |
/* | |
编译选项: | |
-I /usr/include/python2.7 | |
链接选项: | |
-lpython2.7 | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python:IP 地址和 MAC 地址转换 | |
# | |
def pack_ip(ipstr): | |
return struct.unpack('L', socket.inet_aton(ipstr))[0] | |
# 结果为 unsigned long | |
def pack_mac(macstr): | |
return struct.pack('BBBBBB', *[ int(i,16) for i in macstr.split(':') ]) | |
# 结果为 char mac[6] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment