swift和带有指针的c函数

swift and c++ function with pointers

我必须在项目中使用大C文件。在此文件中,具有公共功能的类Detect

1
2
3
void processFrame_new(const unsigned char *frame_i, int width_i, int height_i,
                      uint timestamp, int &state, int &index, int &x, int &y,
                      int &debug);

据我了解,我可以通过指针状态,索引,x,y,调试从此函数获得结果。
此函数中的计算需要时间,因此获取结果是异步问题。如何调用此函数并获得结果?

PS感谢rob mayoff现在,我了解了如何packageC代码。最后一个问题"如果processFrame_new(...)内部的计算需要一些时间,如何观察WrapperReturnValue的变化?"


您不能直接从Swift调用C接口,因为导入程序仅理解C和Objective-C,而不能理解C。因此,您需要使用严格的C或Objective-C接口编写package器。

例如,您可以在头文件中声明一个Cpackage函数,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// wrapper.h

#ifndef wrapper_h
#define wrapper_h

#ifdef __cplusplus
extern"C" {
#endif

typedef struct {
    int state;
    int index;
    int x;
    int y;
    int debug;
} WrapperReturnValue;

WrapperReturnValue wrapped_processFrame_new(const unsigned char *frame, int width, int height, unsigned int timestamp);

#ifdef __cplusplus
}
#endif

#endif /* wrapper_hpp */

在桥接头中,您可以导入wrapper.h以使WrapperReturnValuewrapped_processFrame_new可用于Swift:

1
2
3
4
5
6
7
// test-Bridging-Header.h

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import"wrapper.h"

然后可以在C中实现package函数,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
// wrapper.cpp

#include"wrapper.h"

void processFrame_new(const unsigned char *frame_i, int width_i, int height_i,
                      unsigned int timestamp, int &state, int &index, int &x, int &y,
                      int &debug);

WrapperReturnValue wrapped_processFrame_new(const unsigned char *frame, int width, int height, unsigned int timestamp) {
    WrapperReturnValue r = {};
    processFrame_new(frame, width, height, timestamp, r.state, r.index, r.x, r.y, r.debug);
    return r;
}