Skip to content

Add swift binding #327

Closed
Closed

Description

@Andrey1994

Use other languages(java, c#, python) as an API reference.

Useful link: https://stackoverflow.com/questions/34669958/swift-how-to-call-a-c-function-loaded-from-a-dylib

Activity

  1. ScottThomasMiller commented on Aug 19, 2021

    @ScottThomasMiller

    I am trying to create a bridging header for Swift 5 and Xcode 12.5.1. Must my Swift code instantiate the BoardShim object, or can it just call prepare_session() and start_stream() directly?

  2. Andrey1994 commented on Aug 19, 2021

    @Andrey1994
    MemberAuthor

    The idea of bindings is to provide high-level API which is easier to use than plain C methods exposed from low-level library. So, we created BoardShim class for each binding. Users are expected to work with BoardShim methods instead calling low-level prepare_session and other methods directly.

    Example from Java:(https://github.com/brainflow-dev/brainflow/blob/master/java-package/brainflow/src/main/java/brainflow/BoardShim.java)

        public void prepare_session () throws BrainFlowError
        {
            int ec = instance.prepare_session (board_id, input_json);
            if (ec != ExitCode.STATUS_OK.get_code ())
            {
                throw new BrainFlowError ("Error in prepare_session", ec);
            }
        }
    
  3. Andrey1994 commented on Aug 19, 2021

    @Andrey1994
    MemberAuthor

    So I would say let's create BoardShim, DataFilter, and other classes like in existing bindings

  4. Andrey1994 commented on Aug 19, 2021

    @Andrey1994
    MemberAuthor

    I dont know swift but why do we need a bridging header at all?(and what is it?)

    I think it can look like this(pseudocode inspired from python binding):

    class BoardShimDynLibLoader {
        handler = nil;
        static func get_handler() {
            if (handler == nil)
                handler = dlopen("libBoardContoller.dylib", RTLD_NOW)
            return handler;
    }
    
    class BoardShim {
        func prepare_session() {
            typealias prepare_session = @convention(c) (CInt, Cchar *) -> CInt
            handler = BoardShimDynLibLoader.get_handler()
            var prepare_session = dlsym(handle, "prepare_session")
            if (prepare_session != nil) {
                let f = unsafeBitCast(sym, prepare_session .self)
                let result = f(board_id, params)
           }
        }    
    }
    

    Idea is to create a singleton that will call dlopen only once and find addresses of required functions manually.
    Is it worse or better?(I don't know swift best practices)

  5. ScottThomasMiller commented on Aug 19, 2021

    @ScottThomasMiller

    The bridging header tells Swift how to resolve the object names in your Swift code. Without it you get errors such as, "Cannot find 'prepare_stream' in scope". It's typically a .h file which simply includes other .h files. You have to register it in the Xcode build settings, so that Swift knows where to look.

    Your example is similar to this: https://stackoverflow.com/questions/35229149/interacting-with-c-classes-from-swift

    I should be able to implement something like the that, because I already have all of BrainFlow's C++ headers.

    I am still learning Swift, but I think that your idea is basically a wrapper, and wrappers are very "Swifty".

  6. ScottThomasMiller commented on Aug 23, 2021

    @ScottThomasMiller

    I managed to call the low-level functions directly, such as prepare_session() and get_eeg_channels(), but so far I am unable to instantiate BoardShim(). I need some help. Everything I've found so far, I can't get working.

  7. Andrey1994 commented on Aug 23, 2021

    @Andrey1994
    MemberAuthor

    You should not call methods from C++ BoardShim class. This class even doesn't exist in low-level API(low-level API is for bindings, high-level API is for users).

    Instead, you need to create a new class in Swift and call it BoardShim, inside this class you need to wrap methods from low-level API. Take a look at the cpp-package for reference. https://github.com/brainflow-dev/brainflow/blob/master/cpp-package/src/board_shim.cpp#L104 Here method is_prepared from BoardShim class wraps method is_prepared from low-level API, you need to do the same

  8. ScottThomasMiller commented on Aug 23, 2021

    @ScottThomasMiller

    OK I think I finally understand: you want me to write BoardShim.swift modeled after board_shim.cpp. That seems completely doable. I will also have to write swift bindings for all of BoardShim's dependencies, such as BrainFlowException, BrainFlowArray, BrainFlowInputParams, etc. And nowhere in all of those bindings will I need to instantiate any C++ classes, correct?

  9. Andrey1994 commented on Aug 23, 2021

    @Andrey1994
    MemberAuthor

    Correct, but probably you dont need BrainFlowArray(its specific for c++ for better perf, you can do the same as in java for example). Also, there are two more classes: DataFilter and MLModule, its the same there.(I can help and do it for some of them)

  10. Andrey1994 commented on Aug 23, 2021

    @Andrey1994
    MemberAuthor

    Also, you need to duplicate enums like BoardIds, etc. All of that is pretty small and simple except main classes(BoardShim and DataFilter)

  11. ScottThomasMiller commented on Aug 24, 2021

    @ScottThomasMiller
  12. Andrey1994 commented on Aug 24, 2021

    @Andrey1994
    MemberAuthor

    Looks good so far!

  13. ScottThomasMiller commented on Aug 24, 2021

    @ScottThomasMiller

    Thanks. Swift doesn't like binding its String type to "char *" parameters in its bridging headers, so I'm making them all "const char *" in board_controller.h instead.

    Also I think Swift will automatically make BoardIds iterable if I add the CaseIterable protocol to its type definition. I'll try that shortly.

  14. 31 remaining items

  15. ScottThomasMiller commented on Sep 9, 2021

    @ScottThomasMiller

    I'm not yet sure how to do the same in Swift, nor am I certain it's necessary.

    I am ready to push BoardShim.swift and its dependencies. Please give me instructions for committing and pushing.

  16. Andrey1994 commented on Sep 9, 2021

    @Andrey1994
    MemberAuthor

    <<I'm not yet sure how to do the same in Swift, nor am I certain it's necessary.

    This stuff with instance in java is kinda bridging header in swift. It describes the interface of BoardController.dll and allows you to call C\C++ methods. You don't need that.

    <<I am ready to push BoardShim.swift and its dependencies. Please give me instructions for committing and pushing.

    Create WIP PR from non-master branch of your fork and if you see a checkbox like "allow edit to maintainers" click on it. So, I will be able to make changes and help you a little. Make sure that swift binding matches the common structure in terms of folder and file names. Would be good to add a few tests to CI pipelines but it can be done later on

  17. ScottThomasMiller commented on Sep 9, 2021

    @ScottThomasMiller

    In my fork should I duplicate ./brainflow/settings.xml and ./brainflow/pom.xml?

  18. Andrey1994 commented on Sep 9, 2021

    @Andrey1994
    MemberAuthor

    no, these files are specific for maven packaging(like setup.py in python)

  19. ScottThomasMiller commented on Sep 9, 2021

    @ScottThomasMiller

    I created my fork and within it a branch named swift-bindings. I cloned that branch to my laptop, added my .swift files, committed and pushed them, and now am ready to create my pull request. How do I make it WIP?

    Here's a screenshot:

    image

  20. Andrey1994 commented on Sep 9, 2021

    @Andrey1994
    MemberAuthor

    Green Button "Create pull Request" click on triangle close to it

  21. ScottThomasMiller commented on Sep 9, 2021

    @ScottThomasMiller

    "Create draft pull request"?

  22. Andrey1994 commented on Sep 9, 2021

    @Andrey1994
    MemberAuthor

    yes

  23. ScottThomasMiller commented on Sep 11, 2021

    @ScottThomasMiller

    Because of the Swift scope rules, I had to move the logger functions of DataFilter inside its type definition. Otherwise it would have caused name collisions with the analogous BoardShim functions. For consistency I should probably do the same for the BoardShim logger functions. What do you think?

  24. Andrey1994 commented on Sep 11, 2021

    @Andrey1994
    MemberAuthor

    I think all methods like get_exg_channels ,set_log_level, etc should be static class methods instead of global functions. This way it will be consistent with other bindings

  25. Andrey1994 commented on Sep 11, 2021

    @Andrey1994
    MemberAuthor

    In fact there should not be any global functions, only class methods and static class methods

  26. Andrey1994 commented on Sep 11, 2021

    @Andrey1994
    MemberAuthor

    And lets move this discussion to PR comments

  27. hab25 commented on May 9, 2025

    @hab25

    Looks like cf90732 may have solved this for macOS only, iOS still wanted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions