このページのチュートリアルに従おうとしています(独自の単純な「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() はどちらも空の文字列を返します! 何を与える?
私のソースファイル
単語一口
%Module word
class Word {
%TypeHeaderCode
#include <word.h>
%End
public:
Word(const char *w);
char *reverse() const;
char *get() const;
};
単語.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;
}
ワード.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()
lib をコンパイルして /usr/lib に移動するためのシェル スクリプト
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