1.编译sip源码
- 解压sip源码,运行
python configure.py -p win32-g++
(win32-g++表示使用mingw32编译器)。 - 修改生成的
sipconfig.py
文件。当Python安装在C:\Program Files (x86)
目录时,把_pkg_config中Program Files (x86)
替换为Progra~2
,修改后如下所示:
_pkg_config = {
'arch': '',
'default_bin_dir': 'C:\\Progra~2\\Python',
'default_mod_dir': 'C:\\Progra~2\\Python\\Lib\\site-packages',
'default_sip_dir': 'C:\\Progra~2\\Python\\sip',
'deployment_target': '',
'platform': 'win32-g++',
'py_conf_inc_dir': 'C:\\Progra~2\\Python\\include',
'py_inc_dir': 'C:\\Progra~2\\Python\\include',
'py_lib_dir': 'C:\\Progra~2\\Python\\libs',
'py_version': 0x030603,
'qt_framework': 0,
'sip_bin': 'C:\\Progra~2\\Python\\sip',
'sip_config_args': '-p win32-g++',
'sip_inc_dir': 'C:\\Progra~2\\Python\\include',
'sip_mod_dir': 'C:\\Progra~2\\Python\\Lib\\site-packages',
'sip_version': 0x041306,
'sip_version_str': '4.19.6',
'universal': ''
}
当Python安装在C:\Program Files
目录下时,把_pkg_config中Program Files
替换为Progra~1
即可。
- 编译,运行
make
,成功之后运行make install
安装sip。其中make install
需要管理员权限。
2. 测试
- 编写C文件
test.c
,如下所示:
#include
int add(int x, int y)
{
return x + y;
}
void hello(char* s)
{
printf("%s\n", s);
}
char* toString(int x, float y)
{
static char s[20];
sprintf(s, "x = %d; y = %f", x, y);
return s;
}
- 编写sip文件
test.sip
。sip文件名必须和.c文件名相同。由于使用的是c语言,必须加上%Module(name=test, language="C")
。内容如下所示:
/* Define the SIP wrapper to the add library. */
%Module(name=test, language="C")
int add(int x, int y);
void hello(char* s);
char* toString(int x, float y);
- 编写
configure.py
,内容如下:
import os
import sipconfig
basename = "test"
# The name of the SIP build file generated by SIP and used by the build
# system.
build_file = basename + ".sbf"
# Get the SIP configuration information.
config = sipconfig.Configuration()
os.system("make clean")
# Run SIP to generate the code.
os.system(" ".join([config.sip_bin, "-c", ".", "-b", build_file, basename + ".sip"]))
os.system(" ".join(['gcc', '-c', basename + ".c"]))
os.system(" ".join(['ar', '-r', "lib" + basename + ".a", basename + ".o"]))
# Create the Makefile.
makefile = sipconfig.SIPModuleMakefile(config, build_file)
# Add the library we are wrapping. The name doesn't include any platform
# specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
# ".dll" extension on Windows).
makefile.extra_libs = [basename]
# Search libraries in current directory
makefile.extra_lflags = ['-L.']
# Generate the Makefile itself.
makefile.generate()
os.system("make")
运行python configure.py
,生成的文件如下所示:
其中test.pyd
即是编译后的文件。
- 测试
import test
a = test.add(12, 3)
print(a)
test.hello('你好啊'.encode())
s = test.toString(12, 45.6)
print(s)
输出:
15
b'x = 12; y = -2.000000'
你好啊
版权声明:本文为「txfly」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://www.jianshu.com/p/34088714381e