1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/native_library.h"
9 #include "base/file_path.h"
10 #include "base/file_util.h"
11 #include "base/mac/scoped_cftyperef.h"
12 #include "base/string_util.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "base/utf_string_conversions.h"
19 NativeLibrary LoadNativeLibrary(const FilePath& library_path,
21 // dlopen() etc. open the file off disk.
22 if (library_path.Extension() == "dylib" ||
23 !file_util::DirectoryExists(library_path)) {
24 void* dylib = dlopen(library_path.value().c_str(), RTLD_LAZY);
27 NativeLibrary native_lib = new NativeLibraryStruct();
28 native_lib->type = DYNAMIC_LIB;
29 native_lib->dylib = dylib;
32 base::mac::ScopedCFTypeRef<CFURLRef> url(
33 CFURLCreateFromFileSystemRepresentation(
35 (const UInt8*)library_path.value().c_str(),
36 library_path.value().length(),
40 CFBundleRef bundle = CFBundleCreate(kCFAllocatorDefault, url.get());
44 NativeLibrary native_lib = new NativeLibraryStruct();
45 native_lib->type = BUNDLE;
46 native_lib->bundle = bundle;
47 native_lib->bundle_resource_ref = CFBundleOpenBundleResourceMap(bundle);
52 void UnloadNativeLibrary(NativeLibrary library) {
53 if (library->type == BUNDLE) {
54 CFBundleCloseBundleResourceMap(library->bundle,
55 library->bundle_resource_ref);
56 CFRelease(library->bundle);
58 dlclose(library->dylib);
64 void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
66 if (library->type == BUNDLE) {
67 base::mac::ScopedCFTypeRef<CFStringRef> symbol_name(
68 CFStringCreateWithCString(kCFAllocatorDefault, name,
69 kCFStringEncodingUTF8));
70 return CFBundleGetFunctionPointerForName(library->bundle, symbol_name);
72 return dlsym(library->dylib, name);
76 string16 GetNativeLibraryName(const string16& name) {
77 return name + ASCIIToUTF16(".dylib");