2015-05-17 72 views
0

許多年來,我一直沒有與C合作過,所以我被困在如何從簡單的庫中獲取一個字符串並轉化爲Python。Python,從C庫中獲取字符串

test.c的

#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 

char * get_string() { 

     char theString[]= "This is my test string!"; 

     char *myString = malloc (sizeof(char) * (strlen(theString)) +1); 

     strcpy(myString, theString); 

     return myString; 
} 

我編譯使用的代碼:

gcc -Wall -O3 -shared test.c -o test.so 

python.py

#!/usr/bin/env python 

import ctypes 

def main(): 
    string_lib = ctypes.cdll.LoadLibrary('test.so') 
    myString = string_lib.get_string() 
    print ctypes.c_char_p(myString).value 

if __name__ == '__main__': 
    main() 

當我運行Python腳本,我得到:

Segmentation fault: 11 

如果我只是打印結果我得到一個數字值,我認爲是指針...我怎樣才能使它工作?

謝謝!

+0

不要在編譯的C代碼,你需要的'-fpic'標誌? –

+0

@PaulRooney - 現在嘗試,結果相同。 – Kostas

回答

2

問題是您正在使用64位Python。這將截斷返回的指針。

首先聲明restype:

import ctypes 

def main(): 
    string_lib = ctypes.cdll.LoadLibrary('test.so') 
    string_lib.get_string.restype = ctypes.c_char_p 
    myString = string_lib.get_string() 
    print myString 

if __name__ == '__main__': 
    main() 
+0

工作!謝謝! – Kostas