1

I'm trying to follow the tutorial on this page (I've also added my own simple 'get' method). I'm getting different results whether I use the interactive or normal Python mode.

Normal mode

word_test.py

from word import Word

foo = Word("reverse me")
print foo.get()
print foo.reverse()

Shell

$ python word_test.py 
reverse me
em esrever

Everything works as expected! Yay!

Interactive mode

Shell

$ 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() and foo.reverse() both return an empty string! What gives?

My source files

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()

Shell script to compile and move the lib to /usr/lib

run.sh (needs root access)

#!/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
Community
  • 1
  • 1
  • 1
    I haven't looked at this SIP library, but it looks to me that you're trying to make C++ available to your python scripts. I recommend you take a look at [Thrift](https://thrift.apache.org/), who knows, it might do the things you want to do, perhaps even better than the SIP library you're currently using. – Loknar May 12 '15 at 23:55

0 Answers0