0

我在 xcode 中将一些 c++ 集成到我的 Objective-c 代码中有点挣扎。我首先编写了一个播放一些音频的 c++ 程序,它运行良好。它由一些函数和一个结构组成。在我尝试将它集成到我的 Objective-C 代码中之前,我做了这样的事情:

typedef struct MyPlayer {

//some declarations...

} MyPlayer;
void createInput(MyPlayer *player);
//some other functions...

在 c++ 文件的主体中:

int main (int argc, const char * argv[]) {
MyPlayer player = {0};

// create it
createInput(&player);
}

效果很好。

现在我想,好吧,让我们把它带入objective-c

将播放器添加到objective-c代码的头文件中..

并做了这样的事情:

 self.player = {0}; //does not compile, commented it out to test
 createInput(self.player);

并且用 = {0} 注释掉它可以编译,但是当它尝试进入 createInput 时会崩溃。当我有这样一个objective-c + c++项目时,如何使用指针或用{0}填充结构?

为什么要把它放到objective-c中?因为我的界面是内置在objective-c/cocoa

谢谢!本杰明

4

2 回答 2

0

Your problem is that in the Objective-C case, the player structure isn't a local variable - it has assumedly been declared as a property. When you assign a value using self.player, you are essentially calling the property setter method [self setPlayer:{0}] which doesn't make any sense.

Looking at how you're using the code, I'm assuming player is actually declared as a pointer to a MyPlayer struct, so you would need to allocate memory for it. If you use calloc for that you can create the structure and initialise it to zero at the same time.

Something like this:

self.player = calloc(1, sizeof(MyPlayer));

This allocates the memory, sets the contents to zero, and calls the property setter to assign that memory to the player property.

If I've got that wrong, it would help if you showed how player has been declared in the Objective-C code.

于 2013-07-19T11:43:00.777 回答
0

我不知道您如何准确地声明结构对象。但以下代码工作正常

typedef struct myStruct{
  int a;
  int b;
  int c;
}myStruct;

- (void)viewDidLoad
{
    [super viewDidLoad];
    myStruct abc = {0}; //works fine

    // myStruct abc;  
    //self.abc = {0}; //error  

    NSLog(@"%d %d %d",abc.a,abc.b,abc.c);
}
于 2013-07-19T12:04:29.387 回答