【问题标题】:Wrapping c++ class for python (with opencv), gives ERROR为python(使用opencv)包装c ++类,给出错误
【发布时间】:2016-02-05 09:41:47
【问题描述】:

我正在尝试在 .so 文件中生成 C++ 代码并在 python 中导入 .so 文件。我的 C++ 代码是

extern "C" int  top(int a, int b){
return a + b;
}


extern "C" int fark(int a, int b){
return a - b;
}

 extern "C" int carp(int a, int b){
return a * b;
}


extern "C" int bol(int a, int b){
return a / b;
}

extern "C" void foto(string s)
{

Mat im = imread(s, 1);

if (im.empty())
{

    cout << "url hatali" << endl;
}
else
{

    imshow("foto", im);
    waitKey(1000);
}
}

extern "C" void gri(string s){


Mat im = imread(s, 1);

if (im.empty())
{
    cout << "url hatali" << endl;
}
else
{

    cvtColor(im, im, CV_RGB2GRAY);
    imshow("Gri", im);
    waitKey(1000);
}
}

extern "C" void asdf(string s ,int i){

Mat im = imread(s, 1);

if (im.empty())
{
    cout << "url hatali" << endl;
}
else
{

    cvtColor(im, im, CV_RGB2GRAY);
    threshold(im, im, i, 255, THRESH_BINARY);
    imshow("Binary", im);
    waitKey(1000);
}

}

我的生成命令是:g++ -c -fPIC webcam.cpp -o webcam.o -lopencv_core -lopencv_highgui g++ -shared -Wl,-soname,webcam.so -o webcam.so webcam.o

我生成了 .so 文件,但是当我在我的 python 代码中导入我的 .so 文件时,我得到了错误: _ZN2cv6imshowERKNS_6StringERKNS_11_InputArrayE

我的python代码是:

from ctypes import cdll
mydll=cdll.LoadLibrary('/PATH/deneme.so')
print(mydll.top(123,123))
print(mydll.carp(123,123))
print(mydll.fark(123,123))
print(mydll.bol(123,123))

【问题讨论】:

  • std::string 在 C 接口中不起作用,它是一个 C++ 类。

标签: python c++ opencv ctypes


【解决方案1】:

我的生成命令是:g++ -c -fPIC webcam.cpp -o webcam.o -lopencv_core -lopencv_highgui g++ -shared -Wl,-soname,webcam.so -o webcam.so webcam.o

您需要将库放在链接步骤中,而不是编译步骤中。

g++ -c -fPIC webcam.cpp -o webcam.o
g++ -fPIC -shared -Wl,-soname,webcam.so -o webcam.so webcam.o -lopencv_core -lopencv_highgui

正如@πάντα ῥεῖ 所说,在extern "C" 函数的接口中放置std::string 时应该小心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2017-04-25
    • 2015-05-15
    相关资源
    最近更新 更多