1

我正在尝试按照此页面上的教程进行操作(我还添加了自己的简单“获取”方法)。无论我使用交互模式还是普通 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;
};

单词.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;
};

配置文件

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 的 Shell 脚本

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
4

0 回答 0