Search code examples
objective-cxcodemacosdlopenapple-tv

Apple TV - creating and loading dynamic library (dylib)


I would like to load a c/c++ shared object in my Apple TV project. I create a simple library using the following tutorial:

Link

Due to the fact i want to compile and load it into my Apple TV project i did some changes:

  1. The dlopen code is in my ViewController.m on which user press a button and then dlopen is called.

    // Open the library.
    NSString * libraryname = [NSString stringWithFormat:@"libRatings.A"];
    NSString * libraryfullpath = [mainBundle pathForResource:libraryname ofType:@"dylib"];
    
    void *lib_handle = dlopen([libraryfullpath UTF8String], RTLD_NOW);
    if (lib_handle)
    {
     printf("[%s] dlopen(\"%s\", RTLD_NOW): Successful\n", __FILE__,      "library");
    }
    else
    {
        printf("\n\n[%s] Unable to open library: %s\n",
           __FILE__, dlerror());
        exit(EXIT_FAILURE);
    }
    
  2. changed the compilation command to:

    clang -dynamiclib -std=gnu99 -current_version 1.0 -compatibility_version 1.0 -fvisibility=hidden -arch arm64 -mtvos-version-min=9.2 -g -Wno-sign-conversion -fembed-bitcode-marker -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS9.2.sdk Ratings.c -o libRatings.A.dylib
    
  3. I copied my dylib into my project and verified that it is copied as a bundle resource.

When running my app, after dlopen call failed i'm getting the following error:

[/Users/gfsrnd/Documents/sample1/sample1/sample1/ViewController.m] Unable to open library: dlopen(/var/containers/Bundle/Application/CFF7EC2A-7DF5-4270-9E99-2D5FAEBB0275/sample1 copy.app/libRatings.A.dylib, 2): no suitable image found.  Did find:
/var/containers/Bundle/Application/CFF7EC2A-7DF5-4270-9E99-2D5FAEBB0275/sample1 copy.app/libRatings.A.dylib: mmap() error 1 at address=0x1024D4000, size=0x00008000 segment=__TEXT in Segment::map() mapping /var/containers/Bundle/Application/CFF7EC2A-7DF5-4270-9E99-2D5FAEBB0275/sample1 copy.app/libRatings.A.dylib

Result of otool is:

**> otool -TV libRatings.A.dylib**
libRatings.A.dylib:
Table of contents (0 entries)
module name      symbol name

Result of nm is:

    **>nm -ag libRatings.A.dylib**

             U ___stack_chk_fail
             U ___stack_chk_guard
             U ___strncat_chk
    0000000000007d30 T _addRating
    0000000000007ecc T _clearRatings
    0000000000007db8 T _meanRating
                     U _memset
                     U _printf
    0000000000007ebc T _ratings
                     U _strdup
                     U _strlen
                     U dyld_stub_binder

Can anyone please advise what am i doing wrong?

Thanks


Solution

  • Indeed, seems that there is no way to do dynamic loading...

    I just used static linking..