How to use the same C++ code for Android and iOS?

后端 未结 2 1246
梦谈多话
梦谈多话 2020-11-30 15:56

Android with NDK has support to C/C++ code and iOS with Objective-C++ has support too, so how can I write applications with native C/C++ code shared between Android and iOS?

2条回答
  •  生来不讨喜
    2020-11-30 16:36

    Approach described in the excellent answer above can be completely automated by Scapix Language Bridge which generates wrapper code on the fly directly from C++ headers. Here is an example:

    Define your class in C++:

    #include 
    
    class contact : public scapix::bridge::object
    {
    public:
        std::string name();
        void send_message(const std::string& msg, std::shared_ptr from);
        void add_tags(const std::vector& tags);
        void add_friends(std::vector> friends);
    };
    

    And call it from Swift:

    class ViewController: UIViewController {
        func send(friend: Contact) {
            let c = Contact()
    
            contact.sendMessage("Hello", friend)
            contact.addTags(["a","b","c"])
            contact.addFriends([friend])
        }
    }
    

    And from Java:

    class View {
        private contact = new Contact;
    
        public void send(Contact friend) {
            contact.sendMessage("Hello", friend);
            contact.addTags({"a","b","c"});
            contact.addFriends({friend});
        }
    }
    

提交回复
热议问题