如何用C代码包装OpenCV C ++函数

问题描述 投票:0回答:1

我能够运行我的C ++代码来显示图像,但正在尝试将其与其他C代码集成。

我正在寻找有关如何在OpenCV中为我的C ++代码编写C包装程序的演练。以后,我将需要能够在我的C代码中调用此C ++方法!

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    if( argc != 2)
    {
     cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
     return -1;
    }

    Mat image;
    image = imread(argv[1], CV_LOAD_IMAGE_COLOR);   // Read the file

    if(! image.data )                              // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

    namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
    imshow( "Display window", image );                   // Show our image inside it.

    waitKey(0);                                          // Wait for a keystroke in the window
    return 0;
}

这里是我目前正在使用的示例OpenCV C ++代码。

c++ c opencv wrapper
1个回答
0
投票

包装C ++代码,以便C对其进行调用,可以使用一些将自身表现为C函数的C ++函数来完成。例如,假设我有一个名为MyObj的类。

// MyObj.h
#pragma once
#include <iostream>

class MyObj
{
  int m_thing = 42;
public: 
  MyObj() = default;
  ~MyObj() = default;

  void printThing() const {
    std::cout << "MyObj: " << m_thing << std::endl;
  }
  int getThing() const {
    return m_thing;
  }
  void setThing(int v) {
    m_thing = v;
  }
};

我需要将其包装在一些C函数中(用C链接声明)。

// MyObjWrapper.h
#pragma once

/* 
 * use C name mangling if compiling as C++ code. 
 * When compiling as C, this is ignored. 
 */
#ifdef __cplusplus
extern "C" {
#endif

struct ObjWrapper;

/* return a newly created object */
struct ObjWrapper* createObj();

/* delete an object */
void deleteObj(struct ObjWrapper*);

/* do something on an object */
void printThing(const struct ObjWrapper*);

/* get value from object */
int getThing(const struct ObjWrapper*);

/* set value on object */
void setThing(struct ObjWrapper*, int);

#ifdef __cplusplus
}
#endif

现在在C ++包装文件中,我们可以封装所有C ++,仅保留一个C接口。

// MyObjWrapper.cpp
#include "MyObj.h"
#include "MyObjWrapper.h"
#include <cassert>

/* use C name mangling */
#ifdef __cplusplus
extern "C" {
#endif

struct ObjWrapper
{
  MyObj obj;
};

/* return a newly created object */
struct ObjWrapper* createObj()
{
  return new ObjWrapper;
}

/* delete an object */
void deleteObj(struct ObjWrapper* wrapper)
{
  assert(wrapper);
  delete wrapper;
}

/* do something on an object */
void printThing(const struct ObjWrapper* wrapper)
{
  assert(wrapper);
  wrapper->obj.printThing();
}

/* get value from object */
int getThing(const struct ObjWrapper* wrapper)
{
  assert(wrapper);
  return wrapper->obj.getThing();
}

/* set value on object */
void setThing(struct ObjWrapper* wrapper, int thing)
{
  assert(wrapper);
  wrapper->obj.setThing(thing);
}

#ifdef __cplusplus
}
#endif
© www.soinside.com 2019 - 2024. All rights reserved.