简体   繁体   English

带有Objective C类的Mingling C ++类

[英]Mingling C++ classes with Objective C classes

I am using the iphone SDK and coding primarily in C++ while using parts of the SDK in obj-c. 我正在使用iphone SDK并主要使用C ++进行编码,同时在obj-c中使用SDK的部分内容。 Is it possible to designate a C++ class in situations where an obj-c class is needed? 是否可以在需要obj-c类的情况下指定C ++类? For instance: 例如:

1) when setting delegates to obj-c objects. 1)将委托设置为obj-c对象时。

  • I cannot make a C++ class derive from a Delegate protocol so this and possibly other reasons prevent me from making my C++ class a delegate for various obj-c objects. 我不能使一个C ++类派生自Delegate协议,所以这个以及可能的其他原因使我无法使我的C ++类成为各种obj-c对象的委托。 What I do as a solution is create an obj-c adapter class that contains a ptr to the C++ class and is used as the delegate (notifying the C++ class when it is called). 我作为解决方案所做的是创建一个obj-c适配器类,它包含一个到C ++类的ptr并用作委托(在调用时通知C ++类)。 It feels cumbersome to write these every time I need to get delegate notifications to a C++ class. 每次我需要将代理通知写入C ++类时,编写这些内容会很麻烦。

2) when setting selectors 2)设置选择器时

  • This goes hand in hand with item 1. Say I want to set a callback to fire when something is done, like a button press or a setAnimationDidStopSelector in the UIView animation functionality. 这与第1项密切相关。假设我想在完成某些操作时设置回调,例如UIView动画功能中的按钮按下或setAnimationDidStopSelector。 It would be nice to be able to designate a C++ function along with the relevant delegate for setAnimationDelegate. 能够指定C ++函数以及setAnimationDelegate的相关委托将是很好的。

Well, I suspect this isn't readily possible, but if anyone has any suggestions on how to do it if it is, or on how to write such things more easily, I would love to hear them. 嗯,我怀疑这是不可能的,但如果有人对如何做到这一点有任何建议,或者如何更容易地写这些东西,我很乐意听到它们。 Thanks. 谢谢。

The sad news is that you can't get completely around the adapters, but you can ease the job. 令人遗憾的是,你不能完全绕过适配器, 你可以放松工作。 By using the Objective-C runtime libraries you can reduce the clutter by generating the adapters for you with a declarative approach. 通过使用Objective-C运行时库,您可以通过声明方法为您生成适配器,从而减少混乱。

The Objective-C runtime allows you to construct classes at runtime for which you can set the implementation function for the methods. Objective-C运行时允许您在运行时构造类,您可以为其设置方法的实现函数。 Using templates, you can thus generate an Objective-C class from a type-oriented declaration by generating the trampoline functions that invoke the C++ methods that you want. 因此,使用模板,您可以通过生成调用所需C ++方法的trampoline函数,从面向类型的声明生成Objective-C类。

I started a prototype a while back and the state mentioned there might be sufficient in your case. 在一段时间后开始制作原型 ,并且状态提到可能就足够了。 It is possible to do this better and support properties and Distributed Objects cleanly too, but i haven't found the time yet to implement a better version. 有可能更好地完成这项工作并且干净地支持属性和分布式对象,但我还没有找到实现更好版本的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM