如何使用包装器从Swift调用C ++函数并使用终端进行编译?

时间:2019-03-02 17:17:28

标签: c++ swift

这是我的c ++代码:

#include<stdio.h>
#include<string.h>
#include "agg-2.5/include/agg_rendering_buffer.h"
#include "r_buffer.h"
enum{
  frame_width = 320,
  frame_height = 200
};

bool write_ppm(const unsigned char* buf,
                unsigned width,
                unsigned height,
                const char* file_name)
                {
                  FILE* fd = fopen(file_name, "wb");
                  if(fd){
                    fprintf(fd, "P6 %d %d 255 ", width, height);
                    fwrite(buf, 1, width*height*3, fd);
                    fclose(fd);
                    return true;
                  }
                  return false;
                }

void draw_black_frame(agg::rendering_buffer& rbuf){
  unsigned i;
  for(i = 0; i<rbuf.height();i++){
    unsigned char* p = rbuf.row_ptr(i);
    *p++ = 0; *p++ = 0; *p++ = 0;
    p += (rbuf.width() - 2)*3;
    *p++ = 0; *p++ = 0; *p++ = 0;
  }
  memset(rbuf.row_ptr(0), 0, rbuf.width()*3);
  memset(rbuf.row_ptr(rbuf.height()-1), 0, rbuf.width()*3);
}

void start_func() {

  unsigned char* buffer = new unsigned char[frame_width*frame_height*3];

  memset(buffer, 255, frame_width*frame_height*3);

  agg::rendering_buffer rbuf(buffer,
                            frame_width,
                            frame_height,
                            frame_width*3);

  unsigned i;
  for(i = 0; i<rbuf.height()/2;++i){
    unsigned char* ptr = rbuf.row_ptr(i) + i*3;

    *ptr++ = 127;// R
    *ptr++ = 200;// B
    *ptr++ = 98; // G
  }

  draw_black_frame(rbuf);
  write_ppm(buffer, frame_width, frame_height, "agg_test.ppm");

  delete [] buffer;

}

r_buffer.h

extern "C" {
  void start_func();
}

bridge.h

#include "r_buffer.h"

swift_r_buffer.swift

start_func();

我正在尝试如下编译:

swiftc swift_r_buffer.swift -import-objc-header bridge.h

但是出现此错误:

/home/karthik/agg_eg/bridge.h:1:10: note: in file included from /home/karthik/agg_eg/bridge.h:1:
#include "r_buffer.h"
         ^
/home/karthik/agg_eg/./r_buffer.h:1:8: error: expected identifier or '('
extern "C" {
       ^
1 error generated.
<unknown>:0: error: failed to emit precompiled header '/tmp/bridge-238ccd.pch' for bridging header 'bridge.h'
<unknown>:0: error: generate-pch command failed with exit code 1 (use -v to see invocation)

我该如何解决?我正在使用Ubuntu 18.04 LTS。

2 个答案:

答案 0 :(得分:0)

桥必须在C中,因此您需要extern "C"指令以目标为C ++为条件。
像这样:

#ifdef __cplusplus
extern "C" {
#endif

  void start_func(void);

#ifdef __cplusplus
}
#endif

答案 1 :(得分:0)

我解决了这个问题。您需要编译c ++文件

g++ r_buffer.c++ -c

然后建立一个库

ar r libr_buffer.a r_buffer.o

然后按如下所示编译swift文件

swiftc swift_r_buffer.swift libr_buffer.a -import-objc-header bridge.h 

然后您可以按以下方式运行

./main