我正在尝试按照this page上的教程(我还添加了自己的简单'get'方法)。无论我使用交互式还是普通的Python模式,我都会得到不同的结果。
word_test.py
from word import Word
foo = Word("reverse me")
print foo.get()
print foo.reverse()
贝壳
$ python word_test.py
reverse me
em esrever
一切都按预期工作!耶!
贝壳
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from word import Word
>>> foo = Word("reverse me")
>>> print foo.get()
>>> print foo.reverse()
foo.get()和foo.reverse()都返回一个空字符串!是什么给了什么?
word.sip
%Module word
class Word {
%TypeHeaderCode
#include <word.h>
%End
public:
Word(const char *w);
char *reverse() const;
char *get() const;
};
word.cpp
#include <string.h>
#include <iostream>
#include <word.h>
using namespace std;
Word::Word(const char *w)
{
the_word = w;
}
char* Word::reverse() const
{
int len = strlen(the_word);
char *str = new char[len+1];
for (int i = len-1 ; i >= 0 ; i--) {
str[len-1-i] = the_word[i];
}
str[len]='\0';
return str;
}
char* Word::get() const
{
return (char*) the_word;
}
word.h
class Word {
const char *the_word;
public:
Word(const char *w);
char *reverse() const;
char *get() const;
};
configure.py
import os
import sipconfig
# The name of the SIP build file generated by SIP and used by the build
# system.
build_file = "word.sbf"
# Get the SIP configuration information.
config = sipconfig.Configuration()
# Run SIP to generate the code.
os.system(" ".join([config.sip_bin, "-c", ".", "-b", build_file, "word.sip"]))
# 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 = ["word"]
# Generate the Makefile itself.
makefile.generate()
run.sh(需要root访问权限)
#!/bin/bash
python configure.py
g++ -c -fPIC -I. word.cpp
ar -crs libword.a word.o
cp libword.a /usr/lib
make
make install