[英]Create a shared library in C++ to integrate with Python
I need to generate a .so
using this code in C++, to integrate with Python: 我需要使用C ++中的以下代码生成一个.so
,以便与Python集成:
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
// sudo apt-get install libtesseract-dev
// sudo apt-get install libleptonica-dev
extern "C" void read(void) {
Pix *image = pixRead("/home/macabeus/test.jpg");
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
api->Init(NULL, "eng");
api->SetImage(image);
api->SetVariable("save_blob_choices", "T");
api->SetVariable("tessedit_char_whitelist", "QWERTYUIOPASDFGHJKLZXCVBNM");
api->Recognize(NULL);
tesseract::ResultIterator* ri = api->GetIterator();
tesseract::PageIteratorLevel level = tesseract::RIL_SYMBOL;
if(ri != 0) {
do {
const char* symbol = ri->GetUTF8Text(level);
if(symbol != 0) {
tesseract::ChoiceIterator ci(*ri);
do {
const char* choice = ci.GetUTF8Text();
printf("%s(%f)..", choice, ci.Confidence());
} while(ci.Next());
printf("--> recognized as '%s'\n", symbol);
}
delete[] symbol;
} while((ri->Next(level)));
}
}
I use the following command in the terminal to generate the file .so
: 我在终端中使用以下命令来生成文件.so
:
g++ main.cpp -c -fPIC -o main.o
g++ -shared -o main.so main.o
Then generates the file 然后生成文件
main.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=616e7e8e8a094b9c075a21897e8c5d32fc6ea159, not stripped
So, in Python, I use ctypes to use the shared object: 因此,在Python中,我使用ctypes来使用共享对象:
import ctypes
c_lib_test = ctypes.CDLL('cppcodetesseract/main.so')
However, I received the following error message when running code in Python: 但是,在Python中运行代码时收到以下错误消息:
[...]
File "/home/macabeus/ApenasMeu/Dropbox/Python/Extending with C/main.py", line 5, in <module>
c_lib_tes = ctypes.CDLL('cppcodetesseract/main.so')
File "/usr/lib/python3.4/ctypes/__init__.py", line 351, in __init__
self._handle = _dlopen(self._name, mode)
OSError: cppcodetesseract/main.so: undefined symbol: _ZN9tesseract14ChoiceIterator4NextEv
How to solve it? 怎么解决呢? I got success in other codes in C++ that did not use tesseract or leptonica. 我在不使用tesseract或leptonica的C ++其他代码中获得了成功。 But when I use these libraries, I can not succeed. 但是当我使用这些库时,我无法成功。
I resolved my problem: cmake 我解决了我的问题:cmake
I created the file CMakeList.txt
with: 我使用以下命令创建了文件CMakeList.txt
:
add_library(foo SHARED main.cpp)
target_link_libraries (foo lept tesseract)
And so I used the commands cmake .
因此,我使用了cmake .
命令cmake .
and make
. 然后make
。 Then went generated the file libfoo.so
. 然后生成了文件libfoo.so
。 It worked perfectly. 效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.