Linux 下Python調用C++編寫的動態庫


在工程中用到使用Python調用C++編寫的動態庫,結果報如下錯誤:

OSError: ./extract_str.so: undefined symbol: _ZNSt8ios_base4InitD1Ev


Python調用函數

 

 1 #coding:utf-8
 2 from ctypes import *
 3 
 4 libpcre = cdll.LoadLibrary("./extract_str.so")
 5 pcre="^GirlFriend\s+Server\s+\d+\x2E\d+\s+\x2E\s+port\s+\d"
 6 ret = libpcre.extract_exact_strings(pcre, len(pcre), 4, max_str, max_str_len, expr_str, expr_str_len)
 7 if ret == 1: #解析成功
 8 print(ret)
 9 print(max_str)
10 print(expr_str)
11 else: #解析失敗
12 print("ret is not 1!")

 

加載目錄文件

 

報錯:

 

執行nm命令

 

通過搜索知道ios_base4Init 是C++標准輸入輸出函數庫,說明該庫未被加載。搜索知道是由於鏈接的問題。

Stackoverflow鏈接:http://stackoverflow.com/questions/10906275/undefined-reference-to-stdios-baseinitinit


查看Makefile

 1 CC = gcc
 2 CCC = g++
 3 CFLAGS = -g -Wall $(OPEN_O2) -Wstrict-prototypes -fPIC
 4 CPPFLAGS = -g -Wall $(OPEN_O2) -fPIC
 5 INCS = -I../include
 6 SOURCES = $(wildcard *.c *.cpp)
 7 OBJS = $(patsubst %.cpp,%.o, $(patsubst %.c, %.o, $(SOURCES)))
 8 TARGETS = extract_str.a
 9 SHARD_TARGETS = extract_str.so
10 
11 .PHONY: all clean
12 
13 .c.o:
14 $(CC) -c $(CFLAGS) -I. $(INCS) $<
15 .cpp.o:
16 $(CCC) -c $(CPPFLAGS) -I. $(INCS) $<
17 
18 all: $(TARGETS) $(SHARD_TARGETS)
19 
20 clean:
21 rm -f *.a *.o core core.* *~
22 rm ../lib/$(TARGETS)
23 rm ../lib/$(SHARD_TARGETS)
24 
25 $(TARGETS): $(OBJS)
26 ar -cr ../lib/$@ $^
27 
28 $(SHARD_TARGETS): $(OBJS)
29 $(CC) -shared -o ../lib/extract_str.so $^

 

源文件為C++,在生成動態庫時使用的是gcc,導致C++標准庫未被鏈接。兩種修改方式

1. 用g++編譯,命令改為:

 1 $(CCC) -shared -o ../lib/extract_str.so $^ 
2. 繼續使用gcc編譯,添加鏈接參數 –lstdc++ 命令改為:
 1 $(CC) -shared -o ../lib/extract_str.so $^ -lstdc++ 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM