[PyKDE] Help on wrapping a C library

huaicai huaicai at nanorex.com
Mon May 23 19:38:12 BST 2005


Hi all, 

I was trying to use SIP to wrap a C library GTS(gnu triangular surface). I 
am new to the SIP tool, so before wrapping GTS, I am learning to wrap a 
simple C libary just like the C example(word) in the SIP reference guide. 

I implemented the "Word" libary in C and a C test program works fine by 
using the libary. I got a "segmentation fault" error when I call the 
reverse() in python as follows:
              import word
              w = word.create_word("How are you?")
              print word.reverse(w)
I added another reverse function into the "word" library like: "char 
*myReverse(const char *w);". It works fine in python when I do this:
              print word.myReverse("How are you?") 

Please see the C source/header file and SIP specification file in the 
attachments. Can any one tell me what's wrong? 

Thank you very much! I really appreciate your help. 

Huaicai 

-------------- next part --------------
#include "word.h"
#include <string.h>
#include <malloc.h>

struct Word *create_word(const char *w) {
        struct Word *wd;
        wd = (struct Word*)malloc(sizeof(struct Word));
        
        wd->the_word = (char *)malloc((strlen(w) + 1)*sizeof(char));
        strcpy(wd->the_word, w);
        
        return wd;
}

char *reverse(struct Word *word) {
        int ii, len;
        char *newStr;
        char *w = word->the_word;
        
        len = strlen(w);
        newStr = (char *)malloc((len + 1)*sizeof(char));
        for (ii=0; ii<len; ii++)
         newStr[ii] = w[len-ii-1];
        newStr[len] = '\0';
        
        free(word->the_word);
        free(word);
        
        return newStr;
}

char *myReverse(const char *w)  {
        int ii, len;
        char *newStr;
        
        len = strlen(w);
        newStr = (char *)malloc((len + 1)*sizeof(char));
        for (ii=0; ii<len; ii++)
         newStr[ii] = w[len-ii-1];
        newStr[len] = '\0';
        
        return newStr;
}
-------------- next part --------------
#ifndef WORD_H
#define WORD_H

/* Define the interface to the word library. */

struct Word {
    char *the_word;
};

struct Word *create_word(const char *w);
char *reverse(struct Word *word);
char *myReverse(const char *w);

#endif
-------------- next part --------------
/* Define the SIP wrapper to the word library. */

%CModule word 0

struct Word {

%TypeHeaderCode
#include <word.h>
%End

    char *the_word;
};

struct Word *create_word(const char *);
char *reverse(struct Word *);
char *myReverse(const char *);


More information about the PyQt mailing list