如何在C ++头文件中定义字符串参数 - 与Swift桥? [英] How to define string parameters in C++ header file - Bridged with Swift?

查看:311
本文介绍了如何在C ++头文件中定义字符串参数 - 与Swift桥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Xcode项目与Swift和C + +(与桥接头),我试图创建一个函数在C + + 2字符串参数,并返回一个整数数组回到Swift:



.cpp文件

 字符串二)
{
int test [3] = {7,2,3};
return test;
}

.h文件

  #if __cplusplus 
externC{
#endif

int * example一,字符串二); // ERROR HERE

#ifdef __cplusplus
}
#endif

我收到此错误(在.h文件中):


未知类型名称'

我试图在头文件中包含字符串头文件,但是我得到错误(我还必须添加 std :: c>之前<:$ <$> $ <$> $ <$> / strong>

  int * example(std :: string one,std :: string two); 

错误(在第一个 std ::


预期')'


我真的在这里失去了我的耐心,我做错了什么?

解决方案

在externC声明中使用类类型。您可以介绍以下技巧:



标题:

  #if __cplusplus 
externC{
#endif

int * example(void * one,void * two);

#ifdef __cplusplus
}
#endif

source:(.cpp assume)

  #include< string& 
using namespace std;
externC{

int * example(void * one,void * two)
{
string& a = * reinterpret_cast< string *> (一);
string& b = * reinterpret_cast< string *>(two);
...
}
}

by ptr。


I have a Xcode project with Swift and C++ (with bridging header), and I am trying to create a function in C++ with 2 string parameters, and returning an array of integers back to Swift:

.cpp file:

int* example(string one, string two)
{
    int test[3] = {7,2,3};
    return test;
}

.h file:

#if __cplusplus
extern "C" {
#endif

    int* example(string one, string two); //ERROR HERE

#ifdef __cplusplus
}
#endif

I am getting this error (in the .h file):

Unknown type name 'string'

I tried to include the string header file to the header, but then I get the error (I also had to add std:: before the string):

New function declaration:

    int* example(std::string one, std::string two);

Error (at the first std::)

Expected ')'

I am really losing my patience here, what am I doing wrong?

解决方案

You can't use class types in extern "C" declaration. You can introduce the following trick:

header:

#if __cplusplus
extern "C" {
#endif

int* example(void *one, void *two);

#ifdef __cplusplus
}
#endif

source: (.cpp assumed)

#include <string>
using namespace std;
extern "C" {

    int* example(void *one, void *two)
    {
        string &a = *reinterpret_cast<string*>(one);
        string &b = *reinterpret_cast<string*>(two);
    ...
    }
}

You must pass strings by ptr.

这篇关于如何在C ++头文件中定义字符串参数 - 与Swift桥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆