您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ CFRelease函数代码示例

51自学网 2021-06-01 19:58:58
  C++
这篇教程C++ CFRelease函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中CFRelease函数的典型用法代码示例。如果您正苦于以下问题:C++ CFRelease函数的具体用法?C++ CFRelease怎么用?C++ CFRelease使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了CFRelease函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: defined

/** @brief detects current system proxy *  @return QUrl with proxy or empty */QUrl System::systemProxy(void){#if defined(Q_OS_LINUX)    return QUrl(getenv("http_proxy"));#elif defined(Q_OS_WIN32)    HKEY hk;    wchar_t proxyval[80];    DWORD buflen = 80;    long ret;    DWORD enable;    DWORD enalen = sizeof(DWORD);    ret = RegOpenKeyEx(HKEY_CURRENT_USER,        _TEXT("Software//Microsoft//Windows//CurrentVersion//Internet Settings"),        0, KEY_QUERY_VALUE, &hk);    if(ret != ERROR_SUCCESS) return QUrl("");    ret = RegQueryValueEx(hk, _TEXT("ProxyServer"), NULL, NULL, (LPBYTE)proxyval, &buflen);    if(ret != ERROR_SUCCESS) return QUrl("");    ret = RegQueryValueEx(hk, _TEXT("ProxyEnable"), NULL, NULL, (LPBYTE)&enable, &enalen);    if(ret != ERROR_SUCCESS) return QUrl("");    RegCloseKey(hk);    //qDebug() << QString::fromWCharArray(proxyval) << QString("%1").arg(enable);    if(enable != 0)        return QUrl("http://" + QString::fromWCharArray(proxyval));    else        return QUrl("");#elif defined(Q_OS_MACX)    CFDictionaryRef dictref;    CFStringRef stringref;    CFNumberRef numberref;    int enable = 0;    int port = 0;    unsigned int bufsize = 0;    char *buf;    QUrl proxy;    dictref = SCDynamicStoreCopyProxies(NULL);    if(dictref == NULL)        return proxy;    numberref = (CFNumberRef)CFDictionaryGetValue(dictref, kSCPropNetProxiesHTTPEnable);    if(numberref != NULL)        CFNumberGetValue(numberref, kCFNumberIntType, &enable);    if(enable == 1) {        // get proxy string        stringref = (CFStringRef)CFDictionaryGetValue(dictref, kSCPropNetProxiesHTTPProxy);        if(stringref != NULL) {            // get number of characters. CFStringGetLength uses UTF-16 code pairs            bufsize = CFStringGetLength(stringref) * 2 + 1;            buf = (char*)malloc(sizeof(char) * bufsize);            if(buf == NULL) {                qDebug() << "[System] can't allocate memory for proxy string!";                CFRelease(dictref);                return QUrl("");            }            CFStringGetCString(stringref, buf, bufsize, kCFStringEncodingUTF16);            numberref = (CFNumberRef)CFDictionaryGetValue(dictref, kSCPropNetProxiesHTTPPort);            if(numberref != NULL)                CFNumberGetValue(numberref, kCFNumberIntType, &port);            proxy.setScheme("http");            proxy.setHost(QString::fromUtf16((unsigned short*)buf));            proxy.setPort(port);            free(buf);            }    }    CFRelease(dictref);    return proxy;#else    return QUrl("");#endif}
开发者ID:4nykey,项目名称:rockbox,代码行数:80,


示例2: _SCBondInterfaceSetMemberInterfaces

static Boolean_SCBondInterfaceSetMemberInterfaces(SCBondInterfaceRef bond, CFArrayRef members){	CFIndex				i;	SCNetworkInterfacePrivateRef	interfacePrivate	= (SCNetworkInterfacePrivateRef)bond;	CFIndex				n;	CFMutableArrayRef		newMembers;	Boolean				ok			= TRUE;	n = (members != NULL) ? CFArrayGetCount(members) : 0;	// set member interfaces in the stored preferences	if (interfacePrivate->prefs != NULL) {		CFDictionaryRef		dict;		CFMutableDictionaryRef	newDict;		CFStringRef		path;		path = CFStringCreateWithFormat(NULL,						NULL,						CFSTR("/%@/%@/%@"),						kSCPrefVirtualNetworkInterfaces,						kSCNetworkInterfaceTypeBond,						interfacePrivate->entity_device);		dict = SCPreferencesPathGetValue(interfacePrivate->prefs, path);		if (!isA_CFDictionary(dict)) {			// if the prefs are confused			CFRelease(path);			_SCErrorSet(kSCStatusFailed);			return FALSE;		}		newMembers = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);		for (i = 0; i < n; i++) {			SCNetworkInterfaceRef	interface;			CFStringRef		memberName;			interface = CFArrayGetValueAtIndex(members, i);			memberName = SCNetworkInterfaceGetBSDName(interface);			CFArrayAppendValue(newMembers, memberName);		}		newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);		CFDictionarySetValue(newDict, kSCPropVirtualNetworkInterfacesBondInterfaces, newMembers);		CFRelease(newMembers);		if (!CFEqual(dict, newDict)) {			ok = SCPreferencesPathSetValue(interfacePrivate->prefs, path, newDict);		}		CFRelease(newDict);		CFRelease(path);	}	if (ok) {		newMembers = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);		for (i = 0; i < n; i++) {			SCNetworkInterfaceRef		member;			SCNetworkInterfacePrivateRef	newMember;			member = CFArrayGetValueAtIndex(members, i);			newMember = __SCNetworkInterfaceCreateCopy(NULL,								   member,								   interfacePrivate->prefs,								   interfacePrivate->serviceID);			CFArrayAppendValue(newMembers, newMember);			CFRelease(newMember);		}		CFRelease(interfacePrivate->bond.interfaces);		interfacePrivate->bond.interfaces = newMembers;	}	return ok;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:71,


示例3: SCBondInterfaceSetOptions

BooleanSCBondInterfaceSetOptions(SCBondInterfaceRef bond, CFDictionaryRef newOptions){	SCNetworkInterfacePrivateRef	interfacePrivate	= (SCNetworkInterfacePrivateRef)bond;	Boolean				ok			= TRUE;	if (!isA_SCBondInterface(bond)) {		_SCErrorSet(kSCStatusInvalidArgument);		return FALSE;	}	if ((newOptions != NULL) && !isA_CFDictionary(newOptions)) {		_SCErrorSet(kSCStatusInvalidArgument);		return FALSE;	}	// set options in the stored preferences	if (interfacePrivate->prefs != NULL) {		CFDictionaryRef		dict;		CFMutableDictionaryRef	newDict;		CFStringRef		path;		path = CFStringCreateWithFormat(NULL,						NULL,						CFSTR("/%@/%@/%@"),						kSCPrefVirtualNetworkInterfaces,						kSCNetworkInterfaceTypeBond,						interfacePrivate->entity_device);		dict = SCPreferencesPathGetValue(interfacePrivate->prefs, path);		if (!isA_CFDictionary(dict)) {			// if the prefs are confused			CFRelease(path);			_SCErrorSet(kSCStatusFailed);			return FALSE;		}		newDict = CFDictionaryCreateMutableCopy(NULL, 0, dict);		if (newOptions != NULL) {			CFDictionarySetValue(newDict, kSCPropVirtualNetworkInterfacesBondOptions, newOptions);		} else {			CFDictionaryRemoveValue(newDict, kSCPropVirtualNetworkInterfacesBondOptions);		}		if (!CFEqual(dict, newDict)) {			ok = SCPreferencesPathSetValue(interfacePrivate->prefs, path, newDict);		}		CFRelease(newDict);		CFRelease(path);	}	// set options in the SCBondInterfaceRef	if (ok) {		if (interfacePrivate->bond.options != NULL) {			CFRelease(interfacePrivate->bond.options);			interfacePrivate->bond.options = NULL;		}		if (newOptions != NULL) {			interfacePrivate->bond.options = CFDictionaryCreateCopy(NULL, newOptions);		}	}	return ok;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:62,


示例4: _SCBondInterfaceUpdateConfiguration

//.........这里部分代码省略.........					}					a_count = 0;	// all active devices have been removed				}				/*				 * add any devices which are not currently associated				 * with the bond interface.				 */				for (c = 0; c < c_count; c++) {					SCNetworkInterfaceRef		c_interface;					SCNetworkInterfacePrivateRef	c_interfacePrivate;					CFStringRef			c_interface_if;					c_interface = CFArrayGetValueAtIndex(c_bond_interfaces, c);					if ((a_count == 0) ||					    !CFArrayContainsValue(a_bond_interfaces,								  CFRangeMake(0, a_count),								  c_interface)) {						/*						 * check if this member interface can be added to a bond.						 */						c_interfacePrivate = (SCNetworkInterfacePrivateRef)c_interface;						if (!c_interfacePrivate->supportsBond) {							// if member not supported							continue;						}						/*						 * if this member interface is not currently part of the bond.						 */						c_interface_if = SCNetworkInterfaceGetBSDName(c_interface);						if (!__bond_add_interface(s, c_bond_if, c_interface_if)) {							// if member could not be added							ok = FALSE;						}					}				}				break;			}		}		if (!found) {			CFIndex	c;			if (s == -1) {				s = inet_dgram_socket();				if (s == -1) {					_SCErrorSet(errno);					ok = FALSE;					goto done;				}			}			/*			 * establish the new bond interface.			 */			if (!__createInterface(s, c_bond_if)) {				_SCErrorSet(errno);				ok = FALSE;				continue;			}			/* set the mode */			__bond_set_mode(s, c_bond_if, c_bond_mode);			/*			 * add the member interfaces			 */			for (c = 0; c < c_count; c++) {				SCNetworkInterfaceRef		c_interface;				SCNetworkInterfacePrivateRef	c_interfacePrivate;				CFStringRef			c_interface_if;				c_interface = CFArrayGetValueAtIndex(c_bond_interfaces, c);				c_interfacePrivate = (SCNetworkInterfacePrivateRef)c_interface;				if (!c_interfacePrivate->supportsBond) {					// if member not supported					continue;				}				c_interface_if = SCNetworkInterfaceGetBSDName(c_interface);				if (!__bond_add_interface(s, c_bond_if, c_interface_if)) {					// if member could not be added					ok = FALSE;				}			}		}	}    done :	if (active != NULL)	CFRelease(active);	if (config != NULL)	CFRelease(config);	if (s != -1)		(void) close(s);	return ok;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:101,


示例5: _SCBondInterfaceCopyActive

CFArrayRef_SCBondInterfaceCopyActive(void){	struct ifaddrs		*ifap;	struct ifaddrs		*ifp;	int			s;	CFMutableArrayRef	bonds	= NULL;	if (getifaddrs(&ifap) == -1) {		_SCErrorSet(errno);		SCLog(TRUE, LOG_ERR, CFSTR("getifaddrs() failed: %s"), strerror(errno));		return NULL;	}	s = inet_dgram_socket();	if (s == -1) {		_SCErrorSet(errno);		goto done;	}	bonds = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);	for (ifp = ifap; ifp != NULL; ifp = ifp->ifa_next) {		SCBondInterfaceRef		bond;		CFStringRef			bond_if;		struct if_bond_status_req	*ibsr_p;		struct if_data			*if_data;		int				int_val;		CFNumberRef			mode;		CFMutableArrayRef		members		= NULL;		if_data = (struct if_data *)ifp->ifa_data;		if (if_data == NULL		    || ifp->ifa_addr->sa_family != AF_LINK		    || if_data->ifi_type != IFT_IEEE8023ADLAG) {			continue;		}		ibsr_p = if_bond_status_req_copy(s, ifp->ifa_name);		if (ibsr_p == NULL) {			if (errno == EBUSY) {				continue;			}			_SCErrorSet(errno);			SCLog(TRUE, LOG_ERR,			      CFSTR("if_bond_status_req_copy(%s) failed: %s"),			      ifp->ifa_name,			      strerror(errno));			CFRelease(bonds);			bonds = NULL;			goto done;		}		// create the bond interface		bond_if = CFStringCreateWithCString(NULL, ifp->ifa_name, kCFStringEncodingASCII);		bond    = (SCBondInterfaceRef)_SCBondInterfaceCreatePrivate(NULL, bond_if);		CFRelease(bond_if);		// set the mode		int_val = ibsr_p->ibsr_mode;		mode = CFNumberCreate(NULL, kCFNumberIntType, &int_val);		assert(mode != NULL);		_SCBondInterfaceSetMode(bond, mode);		CFRelease(mode);		// add member interfaces		if (ibsr_p->ibsr_total > 0) {			int 			i;			struct if_bond_status *	ibs_p;			// iterate over each member interface			ibs_p = (struct if_bond_status *)ibsr_p->ibsr_buffer;			for (i = 0; i < ibsr_p->ibsr_total; i++) {				CFStringRef	member;				member = CFStringCreateWithCString(NULL, ibs_p[i].ibs_if_name, kCFStringEncodingASCII);				add_interface(&members, member);				CFRelease(member);			}		}		free(ibsr_p);		if (members != NULL) {			_SCBondInterfaceSetMemberInterfaces(bond, members);			CFRelease(members);		}		// add bond		CFArrayAppendValue(bonds, bond);		CFRelease(bond);	}    done :	if (s != -1) {		(void) close(s);	}	freeifaddrs(ifap);	return bonds;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:100,


示例6: CreateNewWindow

bool Shell::OpenWindow(const char* name, bool attach_opengl){	Rect content_bounds = { 60, 20, 60 + 768, 20 + 1024 };	OSStatus result = CreateNewWindow(kDocumentWindowClass,									  kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowLiveResizeAttribute,									  &content_bounds,									  &window);	if (result != noErr)		return false;	CFStringRef window_title = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);	if (result != noErr)		return false;	result = SetWindowTitleWithCFString(window, window_title);	if (result != noErr)	{		CFRelease(window_title);		return false;	}	CFRelease(window_title);	ShowWindow(window);	if (attach_opengl)	{		static GLint attributes[] =		{			AGL_RGBA,			AGL_DOUBLEBUFFER,			AGL_ALPHA_SIZE, 8,			AGL_DEPTH_SIZE, 24,			AGL_STENCIL_SIZE, 8,			AGL_ACCELERATED,			AGL_NONE		};		AGLPixelFormat pixel_format = aglChoosePixelFormat(NULL, 0, attributes);		if (pixel_format == NULL)			return false;		window_port = GetWindowPort(window);		if (window_port == NULL)			return false;		gl_context = aglCreateContext(pixel_format, NULL);		if (gl_context == NULL)			return false;		aglSetDrawable(gl_context, window_port);		aglSetCurrentContext(gl_context);		aglDestroyPixelFormat(pixel_format);				// Set up the GL state.		glClearColor(0, 0, 0, 1);		glEnableClientState(GL_VERTEX_ARRAY);		glEnableClientState(GL_COLOR_ARRAY);		glEnable(GL_BLEND);		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);		glMatrixMode(GL_PROJECTION);		glLoadIdentity();		glOrtho(0, 1024, 768, 0, -1, 1);		glMatrixMode(GL_MODELVIEW);		glLoadIdentity();		opengl_attached = true;	}	return true;}
开发者ID:czbming,项目名称:libRocket,代码行数:76,


示例7: urlWithCredentials

void ResourceHandle::createCFURLConnection(bool shouldUseCredentialStorage, bool shouldContentSniff, CFDictionaryRef clientProperties){    if ((!d->m_user.isEmpty() || !d->m_pass.isEmpty()) && !firstRequest().url().protocolIsInHTTPFamily()) {        // Credentials for ftp can only be passed in URL, the didReceiveAuthenticationChallenge delegate call won't be made.        URL urlWithCredentials(firstRequest().url());        urlWithCredentials.setUser(d->m_user);        urlWithCredentials.setPass(d->m_pass);        firstRequest().setURL(urlWithCredentials);    }    // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication,    // try and reuse the credential preemptively, as allowed by RFC 2617.    if (shouldUseCredentialStorage && firstRequest().url().protocolIsInHTTPFamily()) {        if (d->m_user.isEmpty() && d->m_pass.isEmpty()) {            // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication,             // try and reuse the credential preemptively, as allowed by RFC 2617.            d->m_initialCredential = CredentialStorage::get(firstRequest().url());        } else {            // If there is already a protection space known for the URL, update stored credentials before sending a request.            // This makes it possible to implement logout by sending an XMLHttpRequest with known incorrect credentials, and aborting it immediately            // (so that an authentication dialog doesn't pop up).            CredentialStorage::set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), firstRequest().url());        }    }            if (!d->m_initialCredential.isEmpty()) {        // FIXME: Support Digest authentication, and Proxy-Authorization.        applyBasicAuthorizationHeader(firstRequest(), d->m_initialCredential);    }    RetainPtr<CFMutableURLRequestRef> request = adoptCF(CFURLRequestCreateMutableCopy(kCFAllocatorDefault, firstRequest().cfURLRequest(UpdateHTTPBody)));    wkSetRequestStorageSession(d->m_storageSession.get(), request.get());        if (!shouldContentSniff)        wkSetCFURLRequestShouldContentSniff(request.get(), false);    RetainPtr<CFMutableDictionaryRef> sslProps;#if PLATFORM(IOS)    sslProps = adoptCF(ResourceHandle::createSSLPropertiesFromNSURLRequest(firstRequest()));#else    if (allowsAnyHTTPSCertificateHosts().contains(firstRequest().url().host().lower())) {        sslProps = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsAnyRoot, kCFBooleanTrue);        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsExpiredRoots, kCFBooleanTrue);        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLAllowsExpiredCertificates, kCFBooleanTrue);        CFDictionaryAddValue(sslProps.get(), kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);    }    HashMap<String, RetainPtr<CFDataRef>>::iterator clientCert = clientCerts().find(firstRequest().url().host().lower());    if (clientCert != clientCerts().end()) {        if (!sslProps)            sslProps = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));#if PLATFORM(WIN)        wkSetClientCertificateInSSLProperties(sslProps.get(), (clientCert->value).get());#endif    }#endif // PLATFORM(IOS)    if (sslProps)        CFURLRequestSetSSLProperties(request.get(), sslProps.get());#if PLATFORM(WIN)    if (CFHTTPCookieStorageRef cookieStorage = overridenCookieStorage()) {        // Overridden cookie storage doesn't come from a session, so the request does not have it yet.        CFURLRequestSetHTTPCookieStorage(request.get(), cookieStorage);    }#endif    CFMutableDictionaryRef streamProperties  = CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);    if (!shouldUseCredentialStorage)        CFDictionarySetValue(streamProperties, CFSTR("_kCFURLConnectionSessionID"), CFSTR("WebKitPrivateSession"));#if PLATFORM(IOS) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090)    RetainPtr<CFDataRef> sourceApplicationAuditData = d->m_context->sourceApplicationAuditData();    if (sourceApplicationAuditData)        CFDictionarySetValue(streamProperties, CFSTR("kCFStreamPropertySourceApplication"), sourceApplicationAuditData.get());#endif    static const CFStringRef kCFURLConnectionSocketStreamProperties = CFSTR("kCFURLConnectionSocketStreamProperties");    RetainPtr<CFMutableDictionaryRef> propertiesDictionary;    if (clientProperties)        propertiesDictionary = adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, clientProperties));    else        propertiesDictionary = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));    CFDictionaryAddValue(propertiesDictionary.get(), kCFURLConnectionSocketStreamProperties, streamProperties);    CFRelease(streamProperties);#if PLATFORM(MAC)    if (client() && client()->usesAsyncCallbacks())        d->m_connectionDelegate = adoptRef(new ResourceHandleCFURLConnectionDelegateWithOperationQueue(this));    else        d->m_connectionDelegate = adoptRef(new SynchronousResourceHandleCFURLConnectionDelegate(this));#else    d->m_connectionDelegate = adoptRef(new SynchronousResourceHandleCFURLConnectionDelegate(this));#endif    d->m_connectionDelegate->setupRequest(request.get());//.........这里部分代码省略.........
开发者ID:Happy-Ferret,项目名称:webkit.js,代码行数:101,


示例8: wxMacLaunch

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++////    wxMacLaunch//// argv is the command line split up, with the application path first// flags are the flags from wxExecute// process is the process passed from wxExecute for pipe streams etc.// returns -1 on error for wxEXEC_SYNC and 0 on error for wxEXEC_ASYNC//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++bool wxMacLaunch(char **argv){    // Obtains the number of arguments for determining the size of    // the CFArray used to hold them    CFIndex cfiCount = 0;    for(char** argvcopy = argv; *argvcopy != NULL ; ++argvcopy)    {        ++cfiCount;    }    // If there is not a single argument then there is no application    // to launch    if(cfiCount == 0)    {        wxLogDebug(wxT("wxMacLaunch No file to launch!"));        return false ;    }    // Path to bundle    wxString path = *argv++;    // Create a CFURL for the application path    // Created this way because we are opening a bundle which is a directory    CFURLRef cfurlApp =        CFURLCreateWithFileSystemPath(            kCFAllocatorDefault,            wxCFStringRef(path),            kDefaultPathStyle,            true); //false == not a directory    // Check for error from the CFURL    if(!cfurlApp)    {        wxLogDebug(wxT("wxMacLaunch Can't open path: %s"), path.c_str());        return false ;    }    // Create a CFBundle from the CFURL created earlier    CFBundleRef cfbApp = CFBundleCreate(kCFAllocatorDefault, cfurlApp);    // Check to see if CFBundleCreate returned an error,    // and if it did this was an invalid bundle or not a bundle    // at all (maybe a simple directory etc.)    if(!cfbApp)    {        wxLogDebug(wxT("wxMacLaunch Bad bundle: %s"), path.c_str());        CFRelease(cfurlApp);        return false ;    }    // Get the bundle type and make sure its an 'APPL' bundle    // Otherwise we're dealing with something else here...    UInt32 dwBundleType, dwBundleCreator;    CFBundleGetPackageInfo(cfbApp, &dwBundleType, &dwBundleCreator);    if(dwBundleType != 'APPL')    {        wxLogDebug(wxT("wxMacLaunch Not an APPL bundle: %s"), path.c_str());        CFRelease(cfbApp);        CFRelease(cfurlApp);        return false ;    }    // Create a CFArray for dealing with the command line    // arguments to the bundle    CFMutableArrayRef cfaFiles = CFArrayCreateMutable(kCFAllocatorDefault,                                    cfiCount-1, &kCFTypeArrayCallBacks);    if(!cfaFiles) //This should never happen    {        wxLogDebug(wxT("wxMacLaunch Could not create CFMutableArray"));        CFRelease(cfbApp);        CFRelease(cfurlApp);        return false ;    }    // Loop through command line arguments to the bundle,    // turn them into CFURLs and then put them in cfaFiles    // For use to launch services call    for( ; *argv != NULL ; ++argv)    {        // Check for '<' as this will ring true for        // CFURLCreateWithString but is generally not considered        // typical on mac but is usually passed here from wxExecute        if (wxStrcmp(*argv, wxT("<")) == 0)            continue;        CFURLRef cfurlCurrentFile;    // CFURL to hold file path        wxFileName argfn(*argv);     // Filename for path        if(argfn.DirExists())        {//.........这里部分代码省略.........
开发者ID:CyberIntelMafia,项目名称:clamav-devel,代码行数:101,


示例9: updateScancodes

void updateScancodes(){#ifdef QT_MAC_USE_COCOA    TISInputSourceRef layout = TISCopyCurrentKeyboardLayoutInputSource();    if (!layout) {        qWarning() << "Error retrieving current layout";        return;    }    if (layout == lastLayout) {        CFRelease(layout);    } else {        // keyboard layout changed#ifndef NDEBUG        const void *name = TISGetInputSourceProperty(layout, kTISPropertyLocalizedName);        qDebug() << "Layout changed to: " << CFStringGetCStringPtr((CFStringRef)name, 0);#endif        lastLayout = layout;        scancodes.clear();        CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(layout,                                                kTISPropertyUnicodeKeyLayoutData));        const UCKeyboardLayout *ucData = data ? reinterpret_cast<const UCKeyboardLayout *>(CFDataGetBytePtr(data)) : 0;        if (!ucData) {            qWarning() << "Error retrieving current layout character data";            return;        }        for (int i = 0; i < 128; ++i) {            UInt32 tmpState = 0;            UniChar str[4];            UniCharCount actualLength = 0;            OSStatus err = UCKeyTranslate(ucData, i, kUCKeyActionDown, 0, LMGetKbdType(),                                          kUCKeyTranslateNoDeadKeysMask, &tmpState, 4, &actualLength, str);            if (err != noErr) {                qWarning() << "Error translating unicode key" << err;            } else {                if (str[0] && str[0] != kFunctionKeyCharCode) {                    scancodes.insert(str[0], i);                }            }        }    }#else    KeyboardLayoutRef layout;    if (KLGetCurrentKeyboardLayout(&layout) != noErr) {        qWarning() << "Error retrieving current layout";    }    if (layout != lastLayout) {#ifndef NDEBUG        void *name;        KLGetKeyboardLayoutProperty(layout, kKLName, const_cast<const void **>(&name));        qDebug() << "Layout changed to: " << CFStringGetCStringPtr((CFStringRef) name, 0);#endif        lastLayout = layout;        scancodes.clear();        void *kchr;        if (KLGetKeyboardLayoutProperty(layout, kKLKCHRData, const_cast<const void **>(&kchr)) != noErr) {            qWarning() << "Couldn't load active keyboard layout";        } else {            for (int i = 0; i < 128; i++) {                UInt32 tmpState = 0;                UInt32 chr = KeyTranslate(kchr, i, &tmpState);                if (chr && chr != kFunctionKeyCharCode) {                    scancodes.insert(chr, i);                }            }        }    }#endif}
开发者ID:KDE,项目名称:kwindowsystem,代码行数:71,


示例10: AddEventToPlugin

/****************************************************************************** AddEventToPlugin* -* This method is invoked when launchd wishes the plugin to setup a launch* event matching the parameters in the dictionary.*****************************************************************************/void AddEventToPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken, CFDictionaryRef eventParameters){    CFStringRef domain = CFDictionaryGetValue(eventParameters, sServiceDomainKey);    CFStringRef type = CFDictionaryGetValue(eventParameters, sServiceTypeKey);    CFStringRef name = CFDictionaryGetValue(eventParameters, sServiceNameKey);    CFBooleanRef cfOnAdd = CFDictionaryGetValue(eventParameters, sOnServiceAddKey);    CFBooleanRef cfOnRemove = CFDictionaryGetValue(eventParameters, sOnServiceRemoveKey);    Boolean onAdd = false;    Boolean onRemove = false;    if (cfOnAdd && CFGetTypeID(cfOnAdd) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnAdd))        onAdd = true;    if (cfOnRemove && CFGetTypeID(cfOnRemove) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnRemove))        onRemove = true;    // A type is required. If none is specified, BAIL    if (!type || CFGetTypeID(type) != CFStringGetTypeID())    {        fprintf(stderr, "%s:%s: a LaunchEvent is missing a service type./n", sPluginIdentifier, __FUNCTION__);        return;    }    // If we aren't suppose to launch on services appearing or disappearing, this service does nothing. Ignore.    if (!onAdd && !onRemove)    {        fprintf(stderr, "%s:%s a LaunchEvent is missing both onAdd and onRemove events/n", sPluginIdentifier, __FUNCTION__);        return;    }    // If no domain is specified, assume local.    if (!domain)    {        domain = CFSTR("local");    }    else if (CFGetTypeID(domain) != CFStringGetTypeID() ) // If the domain is not a string, fail    {        fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string./n", sPluginIdentifier, __FUNCTION__);        return;    }    // If we have a name filter, but it's not a string. This event is broken, bail.    if (name && CFGetTypeID(name) != CFStringGetTypeID())    {        fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string./n", sPluginIdentifier, __FUNCTION__);        return;    }    // Get us a browser    NetBrowserInfo* browser = CreateBrowser(plugin, type, domain);    if (!browser)    {        fprintf(stderr, "%s:%s cannot create browser/n", sPluginIdentifier, __FUNCTION__);        return;    }    // Create Event Dictionary    CFMutableDictionaryRef eventDictionary = CFDictionaryCreateMutable(NULL, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);    // We store both the Token and the Dictionary. UserEventAgentSetLaunchEventState needs    // the token and UserEventAgentSetFireEvent needs both the token and the dictionary    CFDictionarySetValue(eventDictionary, sLaunchdTokenKey, launchdToken);    CFDictionarySetValue(eventDictionary, sLaunchdDictKey, eventParameters);    if (name)        CFDictionarySetValue(eventDictionary, sServiceNameKey, name);    // Add to the correct dictionary.    if (onAdd)    {        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to AddEvents", sPluginIdentifier, __FUNCTION__);        AddEventDictionary(eventDictionary, plugin->_onAddEvents, browser);    }    if (onRemove)    {        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to RemoveEvents", sPluginIdentifier, __FUNCTION__);        AddEventDictionary(eventDictionary, plugin->_onRemoveEvents, browser);    }    // Add Token Mapping    CFDictionarySetValue(plugin->_tokenToBrowserMap, launchdToken, browser);    // Release Memory    CFRelease(eventDictionary);}
开发者ID:thenewwazoo,项目名称:Community-mdnsResponder,代码行数:94,


示例11: CreateBrowser

/****************************************************************************** CreateBrowser* -* This method returns a NetBrowserInfo that is looking for a type of* service in a domain. If no browser exists, it will create one and return it.*****************************************************************************/NetBrowserInfo* CreateBrowser(BonjourUserEventsPlugin* plugin, CFStringRef type, CFStringRef domain){    CFIndex i;    CFIndex count = CFDictionaryGetCount(plugin->_browsers);    NetBrowserInfo* browser = NULL;    CFDictionaryRef* dicts = malloc(count * sizeof(CFDictionaryRef));    NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));    // Fetch the values of the browser dictionary    CFDictionaryGetKeysAndValues(plugin->_browsers, (const void**)browsers, (const void**)dicts);    // Loop thru the browsers list and see if we can find a matching one.    for (i = 0; i < count; ++i)    {        CFDictionaryRef browserDict = dicts[i];        CFStringRef browserType = CFDictionaryGetValue(browserDict, sServiceTypeKey);        CFStringRef browserDomain = CFDictionaryGetValue(browserDict, sServiceDomainKey);        // If we have a matching browser, break        if ((CFStringCompare(browserType, type, kCFCompareCaseInsensitive) == kCFCompareEqualTo) &&            (CFStringCompare(browserDomain, domain, kCFCompareCaseInsensitive) == kCFCompareEqualTo))        {            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: found a duplicate browser/n", sPluginIdentifier, __FUNCTION__);            browser = browsers[i];            NetBrowserInfoRetain(NULL, browser);            break;        }    }    // No match found, lets create one!    if (!browser)    {        browser = NetBrowserInfoCreate(type, domain, plugin);        if (!browser)        {            fprintf(stderr, "%s:%s failed to search for %s.%s", sPluginIdentifier, __FUNCTION__, CStringFromCFString(type), CStringFromCFString(domain));            free(dicts);            free(browsers);            return NULL;        }        // Service browser created, lets add this to ourselves to the dictionary.        CFMutableDictionaryRef browserDict = CFDictionaryCreateMutable(NULL, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);        CFDictionarySetValue(browserDict, sServiceTypeKey, type);        CFDictionarySetValue(browserDict, sServiceDomainKey, domain);        // Add the dictionary to the browsers dictionary.        CFDictionarySetValue(plugin->_browsers, browser, browserDict);        NetBrowserInfoRelease(NULL, browser);        // Release Memory        CFRelease(browserDict);    }    free(dicts);    free(browsers);    return browser;}
开发者ID:thenewwazoo,项目名称:Community-mdnsResponder,代码行数:71,


示例12: sizeof

//.........这里部分代码省略.........			str = "T/F";			break;		case kAudioUnitParameterUnit_Percent:		case kAudioUnitParameterUnit_EqualPowerCrossfade:			str = "%";			break;		case kAudioUnitParameterUnit_Seconds:			str = "Secs";			break;		case kAudioUnitParameterUnit_SampleFrames:			str = "Samps";			break;		case kAudioUnitParameterUnit_Phase:		case kAudioUnitParameterUnit_Degrees:			str = "Degr.";			break;		case kAudioUnitParameterUnit_Hertz:			str = "Hz";			break;		case kAudioUnitParameterUnit_Cents:		case kAudioUnitParameterUnit_AbsoluteCents:			str = "Cents";			break;		case kAudioUnitParameterUnit_RelativeSemiTones:			str = "S-T";			break;		case kAudioUnitParameterUnit_MIDINoteNumber:		case kAudioUnitParameterUnit_MIDIController:			str = "MIDI";				//these are inclusive, so add one value here			mNumIndexedParams = short(mParamInfo.maxValue+1 - mParamInfo.minValue);			break;		case kAudioUnitParameterUnit_Decibels:			str = "dB";			break;		case kAudioUnitParameterUnit_MixerFaderCurve1:		case kAudioUnitParameterUnit_LinearGain:			str = "Gain";			break;		case kAudioUnitParameterUnit_Pan:			str = "L/R";			break;		case kAudioUnitParameterUnit_Meters:			str = "Mtrs";			break;		case kAudioUnitParameterUnit_Octaves:			str = "8ve";			break;		case kAudioUnitParameterUnit_BPM:			str = "BPM";			break;		case kAudioUnitParameterUnit_Beats:			str = "Beats";			break;		case kAudioUnitParameterUnit_Milliseconds:			str = "msecs";			break;		case kAudioUnitParameterUnit_Ratio:			str = "Ratio";			break;		case kAudioUnitParameterUnit_Indexed:			{				propertySize = sizeof(mNamedParams);				err = AudioUnitGetProperty (au, 									kAudioUnitProperty_ParameterValueStrings,									scope, 									param, 									&mNamedParams, 									&propertySize);				if (!err && mNamedParams) {					mNumIndexedParams = CFArrayGetCount(mNamedParams);				} else {						//these are inclusive, so add one value here					mNumIndexedParams = short(mParamInfo.maxValue+1 - mParamInfo.minValue);				}				str = NULL;			}			break;		case kAudioUnitParameterUnit_CustomUnit:		{			CFStringRef unitName = mParamInfo.unitName;			static char paramStr[256];			CFStringGetCString (unitName, paramStr, 256, kCFStringEncodingUTF8);			if (mParamInfo.flags & kAudioUnitParameterFlag_CFNameRelease)				CFRelease (unitName);			str = paramStr;			break;		}		case kAudioUnitParameterUnit_Generic:		case kAudioUnitParameterUnit_Rate:		default:			str = NULL;			break;	}		if (str)		mParamTag = CFStringCreateWithCString(NULL, str, kCFStringEncodingUTF8);	else		mParamTag = NULL;}
开发者ID:11020156,项目名称:SampleCode,代码行数:101,


示例13:

CAAUParameter::~CAAUParameter(){	if (mParamName) CFRelease(mParamName);	if (mParamTag) CFRelease(mParamTag);	if (mNamedParams) CFRelease (mNamedParams);}
开发者ID:11020156,项目名称:SampleCode,代码行数:6,


示例14: process_pending_events

struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id){	struct hid_device_info *root = NULL; // return object	struct hid_device_info *cur_dev = NULL;	CFIndex num_devices;	int i;		/* Set up the HID Manager if it hasn't been done */	if (hid_init() < 0)		return NULL;		/* give the IOHIDManager a chance to update itself */	process_pending_events();	/* Get a list of the Devices */	CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);	/* Convert the list into a C array so we can iterate easily. */		num_devices = CFSetGetCount(device_set);	IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));	CFSetGetValues(device_set, (const void **) device_array);	/* Iterate over each device, making an entry for it. */		for (i = 0; i < num_devices; i++) {		unsigned short dev_vid;		unsigned short dev_pid;		#define BUF_LEN 256		wchar_t buf[BUF_LEN];		char cbuf[BUF_LEN];		IOHIDDeviceRef dev = device_array[i];        if (!dev) {            continue;        }		dev_vid = get_vendor_id(dev);		dev_pid = get_product_id(dev);		/* Check the VID/PID against the arguments */		if ((vendor_id == 0x0 && product_id == 0x0) ||		    (vendor_id == dev_vid && product_id == dev_pid)) {			struct hid_device_info *tmp;			size_t len;		    	/* VID/PID match. Create the record. */			tmp = malloc(sizeof(struct hid_device_info));			if (cur_dev) {				cur_dev->next = tmp;			}			else {				root = tmp;			}			cur_dev = tmp;			// Get the Usage Page and Usage for this device.			cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));			cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));			/* Fill out the record */			cur_dev->next = NULL;			len = make_path(dev, cbuf, sizeof(cbuf));			cur_dev->path = strdup(cbuf);			/* Serial Number */			get_serial_number(dev, buf, BUF_LEN);			cur_dev->serial_number = dup_wcs(buf);			/* Manufacturer and Product strings */			get_manufacturer_string(dev, buf, BUF_LEN);			cur_dev->manufacturer_string = dup_wcs(buf);			get_product_string(dev, buf, BUF_LEN);			cur_dev->product_string = dup_wcs(buf);						/* VID/PID */			cur_dev->vendor_id = dev_vid;			cur_dev->product_id = dev_pid;			/* Release Number */			cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));			/* Interface Number (Unsupported on Mac)*/			cur_dev->interface_number = -1;		}	}		free(device_array);	CFRelease(device_set);		return root;}
开发者ID:micuat,项目名称:ofxSpidarMouse,代码行数:90,


示例15: SecTaskLoadEntitlements

static bool SecTaskLoadEntitlements(SecTaskRef task, CFErrorRef *error){    CFMutableDictionaryRef entitlements = NULL;    struct csheader header;    uint8_t *buffer = NULL;    uint32_t bufferlen;    int ret;        ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, &header, sizeof(header));    /* Any other combination means no entitlements */	if (ret == -1) {		if (errno != ERANGE) {            int entitlementErrno = errno;			uint32_t cs_flags = -1;            if (-1 == csops_task(task, CS_OPS_STATUS, &cs_flags, sizeof(cs_flags))) {                syslog(LOG_NOTICE, "Failed to get cs_flags, error=%d", errno);            }			if (cs_flags != 0) {	// was signed	            syslog(LOG_NOTICE, "SecTaskLoadEntitlements failed error=%d cs_flags=%x, task->pid_self=%d", entitlementErrno, cs_flags, task->pid_self);	// to ease diagnostics				CFStringRef description = SecTaskCopyDebugDescription(task);				char *descriptionBuf = NULL;				CFIndex descriptionSize = CFStringGetLength(description) * 4;				descriptionBuf = (char *)malloc(descriptionSize);				if (!CFStringGetCString(description, descriptionBuf, descriptionSize, kCFStringEncodingUTF8)) {					descriptionBuf[0] = 0;				}				syslog(LOG_NOTICE, "SecTaskCopyDebugDescription: %s", descriptionBuf);				CFRelease(description);				free(descriptionBuf);			}			task->lastFailure = entitlementErrno;	// was overwritten by csops_task(CS_OPS_STATUS) above			// EINVAL is what the kernel says for unsigned code, so we'll have to let that pass			if (entitlementErrno == EINVAL) {				task->entitlementsLoaded = true;				return true;			}			ret = entitlementErrno;	// what really went wrong			goto out;		// bail out		}        bufferlen = ntohl(header.length);        /* check for insane values */        if (bufferlen > 1024 * 1024 || bufferlen < 8) {            ret = E2BIG;            goto out;        }        buffer = malloc(bufferlen);        if (buffer == NULL) {            ret = ENOMEM;            goto out;        }        ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, buffer, bufferlen);        if (ret) {            ret = errno;            goto out;        }        CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, buffer+8, bufferlen-8, kCFAllocatorNull);        entitlements = (CFMutableDictionaryRef) CFPropertyListCreateWithData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, NULL, error);        CFRelease(data);        if((entitlements==NULL) || (CFGetTypeID(entitlements)!=CFDictionaryGetTypeID())){            ret = EDOM;	// don't use EINVAL here; it conflates problems with syscall error returns            goto out;        }    }    task->entitlements = entitlements ? CFRetain(entitlements) : NULL;    task->entitlementsLoaded = true;out:    if(entitlements)        CFRelease(entitlements);    if(buffer)        free(buffer);    if (ret && error && *error==NULL)        *error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, ret, NULL);    return ret == 0;}
开发者ID:darlinghq,项目名称:darling-security,代码行数:84,


示例16: hid_open_path

hid_device * HID_API_EXPORT hid_open_path(const char *path){  	int i;	hid_device *dev = NULL;	CFIndex num_devices;		dev = new_hid_device();	/* Set up the HID Manager if it hasn't been done */	if (hid_init() < 0)		return NULL;	/* give the IOHIDManager a chance to update itself */	process_pending_events();	CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);		num_devices = CFSetGetCount(device_set);	IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));	CFSetGetValues(device_set, (const void **) device_array);		for (i = 0; i < num_devices; i++) {		char cbuf[BUF_LEN];		size_t len;		IOHIDDeviceRef os_dev = device_array[i];				len = make_path(os_dev, cbuf, sizeof(cbuf));		if (!strcmp(cbuf, path)) {			// Matched Paths. Open this Device.			IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeNone);			if (ret == kIOReturnSuccess) {				char str[32];				free(device_array);				CFRetain(os_dev);				CFRelease(device_set);				dev->device_handle = os_dev;								/* Create the buffers for receiving data */				dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev);				dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));								/* Create the Run Loop Mode for this device.				   printing the reference seems to work. */				sprintf(str, "HIDAPI_%p", os_dev);				dev->run_loop_mode = 					CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);								/* Attach the device to a Run Loop */				IOHIDDeviceRegisterInputReportCallback(					os_dev, dev->input_report_buf, dev->max_input_report_len,					&hid_report_callback, dev);				IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, hid_device_removal_callback, NULL);								/* Start the read thread */				pthread_create(&dev->thread, NULL, read_thread, dev);				/* Wait here for the read thread to be initialized. */				pthread_barrier_wait(&dev->barrier);								return dev;			}			else {				goto return_error;			}		}	}return_error:	free(device_array);	CFRelease(device_set);	free_hid_device(dev);	return NULL;}
开发者ID:micuat,项目名称:ofxSpidarMouse,代码行数:73,


示例17: setHTTPBody

void setHTTPBody(CFMutableURLRequestRef request, PassRefPtr<FormData> formData){    if (!formData) {        if (wkCanAccessCFURLRequestHTTPBodyParts())            wkCFURLRequestSetHTTPRequestBodyParts(request, 0);        return;    }    size_t count = formData->elements().size();    if (count == 0)        return;    // Handle the common special case of one piece of form data, with no files.    if (count == 1) {        const FormDataElement& element = formData->elements()[0];        if (element.m_type == FormDataElement::data) {            CFDataRef data = CFDataCreate(0, reinterpret_cast<const UInt8 *>(element.m_data.data()), element.m_data.size());            CFURLRequestSetHTTPRequestBody(request, data);            CFRelease(data);            return;        }    }    if (wkCanAccessCFURLRequestHTTPBodyParts()) {        RetainPtr<CFMutableArrayRef> array(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));        for (size_t i = 0; i < count; ++i) {            const FormDataElement& element = formData->elements()[i];            if (element.m_type == FormDataElement::data) {                RetainPtr<CFDataRef> data(AdoptCF, CFDataCreate(0, reinterpret_cast<const UInt8*>(element.m_data.data()), element.m_data.size()));                CFArrayAppendValue(array.get(), data.get());            } else {                RetainPtr<CFStringRef> filename(AdoptCF, element.m_filename.createCFString());                CFArrayAppendValue(array.get(), filename.get());            }        }        wkCFURLRequestSetHTTPRequestBodyParts(request, array.get());        return;    }    // Precompute the content length so CFURLConnection doesn't use chunked mode.    bool haveLength = true;    long long length = 0;    for (size_t i = 0; i < count; ++i) {        const FormDataElement& element = formData->elements()[i];        if (element.m_type == FormDataElement::data)            length += element.m_data.size();        else {            long long size;            if (getFileSize(element.m_filename, size))                length += size;            else                haveLength = false;        }    }    if (haveLength) {        CFStringRef lengthStr = CFStringCreateWithFormat(0, 0, CFSTR("%lld"), length);        CFURLRequestSetHTTPHeaderFieldValue(request, CFSTR("Content-Length"), lengthStr);        CFRelease(lengthStr);    }    static WCReadStreamCallBacks formDataStreamCallbacks =         { 1, formCreate, formFinalize, 0, formOpen, 0, formRead, 0, formCanRead, formClose, 0, 0, 0, formSchedule, formUnschedule };    CFReadStreamRef stream = CFReadStreamCreate(0, (CFReadStreamCallBacks *)&formDataStreamCallbacks, formData.releaseRef());    CFURLRequestSetHTTPRequestBodyStream(request, stream);    CFRelease(stream);}
开发者ID:Czerrr,项目名称:ISeeBrowser,代码行数:71,


示例18: HIDGetDeviceInfo

static voidHIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,                 recDevice * pDevice){    CFMutableDictionaryRef usbProperties = 0;    io_registry_entry_t parent1, parent2;    /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also     * get dictionary for USB properties: step up two levels and get CF dictionary for USB properties     */    if ((KERN_SUCCESS == IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))        && (KERN_SUCCESS == IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))        && (KERN_SUCCESS == IORegistryEntryCreateCFProperties(parent2, &usbProperties, kCFAllocatorDefault, kNilOptions))) {        if (usbProperties) {            CFTypeRef refCF = 0;            /* get device info             * try hid dictionary first, if fail then go to usb dictionary             */            /* get product name */            refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));            if (!refCF) {                refCF = CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name"));            }            if (refCF) {                if (!CFStringGetCString(refCF, pDevice->product, 256, CFStringGetSystemEncoding())) {                    SDL_SetError("CFStringGetCString error retrieving pDevice->product.");                }            }            /* get usage page and usage */            refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey));            if (refCF) {                if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usagePage)) {                    SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");                }                refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsageKey));                if (refCF) {                    if (!CFNumberGetValue (refCF, kCFNumberLongType, &pDevice->usage)) {                        SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");                    }                }            }            refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDVendorIDKey));            if (refCF) {                if (!CFNumberGetValue(refCF, kCFNumberLongType, &pDevice->guid.data[0])) {                    SDL_SetError("CFNumberGetValue error retrieving pDevice->guid[0]");                }            }            refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductIDKey));            if (refCF) {                if (!CFNumberGetValue(refCF, kCFNumberLongType, &pDevice->guid.data[8])) {                    SDL_SetError("CFNumberGetValue error retrieving pDevice->guid[8]");                }            }            /* Check to make sure we have a vendor and product ID               If we don't, use the same algorithm as the Linux code for Bluetooth devices */            {                Uint32 *guid32 = (Uint32*)pDevice->guid.data;                if (!guid32[0] && !guid32[1]) {                    const Uint16 BUS_BLUETOOTH = 0x05;                    Uint16 *guid16 = (Uint16 *)guid32;                    *guid16++ = BUS_BLUETOOTH;                    *guid16++ = 0;                    SDL_strlcpy((char*)guid16, pDevice->product, sizeof(pDevice->guid.data) - 4);                }            }            /* If we don't have a vendor and product ID this is probably a Bluetooth device */            if (NULL == refCF) {    /* get top level element HID usage page or usage */                /* use top level element instead */                CFTypeRef refCFTopElement = 0;                refCFTopElement = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDElementKey));                {                    /* refCFTopElement points to an array of element dictionaries */                    CFRange range = { 0, CFArrayGetCount(refCFTopElement) };                    CFArrayApplyFunction(refCFTopElement, range, HIDTopLevelElementHandler, pDevice);                }            }            CFRelease(usbProperties);        } else {            SDL_SetError("IORegistryEntryCreateCFProperties failed to create usbProperties.");        }        if (kIOReturnSuccess != IOObjectRelease(parent2)) {            SDL_SetError("IOObjectRelease error with parent2");        }        if (kIOReturnSuccess != IOObjectRelease(parent1)) {            SDL_SetError("IOObjectRelease error with parent1");        }    }}
开发者ID:skylersaleh,项目名称:ArgonEngine,代码行数:98,


示例19: RunLoopStarted

static void RunLoopStarted( CFRunLoopObserverRef o, CFRunLoopActivity a, void *sem ){	CFRunLoopObserverInvalidate( o );	CFRelease( o ); // we don't need this any longer	((RageSemaphore *)sem)->Post();}
开发者ID:Highlogic,项目名称:stepmania-event,代码行数:6,


示例20: SCBondInterfaceCopyStatus

//.........这里部分代码省略.........		CFStringRef			interface_name;		struct if_bond_partner_state *	ps;		CFMutableDictionaryRef		status_interface;		int				status_val;		ps = &scan_p->ibs_partner_state;		if (lacp_actor_partner_state_in_sync(scan_p->ibs_state)) {			/* we're in-sync */			status_val = kSCBondStatusOK;			if (lacp_actor_partner_state_in_sync(ps->ibps_state)) {				/* partner is also in-sync */				if (lacp_actor_partner_state_collecting(scan_p->ibs_state)				    && lacp_actor_partner_state_distributing(ps->ibps_state)) {					/* we're able to collect (receive) frames */					collecting = 1;				}				if (lacp_actor_partner_state_distributing(scan_p->ibs_state)				    && lacp_actor_partner_state_collecting(ps->ibps_state)) {					/* we're able to distribute (transmit) frames */					distributing = 1;				}			}		} else {			int			active = 0;			int			status = 0;			static lacp_system	zeroes = { {0, 0, 0, 0, 0, 0}};			if (siocgifmedia(s, scan_p->ibs_if_name, &status, &active) == -1) {				switch (errno) {					case EBUSY :					case ENXIO :						break;					default :						SCLog(TRUE, LOG_ERR,						      CFSTR("siocgifmedia(%s) failed: %s"),						      if_name,						      strerror(errno));						break;				}			}			if (((status & IFM_AVALID) == 0) ||			    ((status & IFM_ACTIVE) == 0) ||			    ((active & IFM_FDX   ) == 0)) {				/* link down or not full-duplex */				status_val = kSCBondStatusLinkInvalid;			} else if ((ps->ibps_system_priority == 0) &&				   (bcmp(&zeroes, &ps->ibps_system, sizeof(zeroes)) == 0)) {				/* no one on the other end of the link */				status_val = kSCBondStatusNoPartner;			} else if (active != bond_if_active) {				/* the link speed was different */				status_val = kSCBondStatusLinkInvalid;			} else {				/* partner is not in the active group */				status_val = kSCBondStatusNotInActiveGroup;			}		}		// interface		strlcpy(if_name, scan_p->ibs_if_name, sizeof(if_name));		interface_name = CFStringCreateWithCString(NULL, if_name, kCFStringEncodingASCII);		interface = _SCNetworkInterfaceCreateWithBSDName(NULL, interface_name,								 kIncludeNoVirtualInterfaces);		CFRelease(interface_name);		// interface status		status_interface = CFDictionaryCreateMutable(NULL,							     0,							     &kCFTypeDictionaryKeyCallBacks,							     &kCFTypeDictionaryValueCallBacks);		num = CFNumberCreate(NULL, kCFNumberIntType, &status_val);		CFDictionarySetValue(status_interface, kSCBondStatusDeviceAggregationStatus, num);		CFRelease(num);		num = CFNumberCreate(NULL, kCFNumberIntType, &collecting);		CFDictionarySetValue(status_interface, kSCBondStatusDeviceCollecting, num);		CFRelease(num);		num = CFNumberCreate(NULL, kCFNumberIntType, &distributing);		CFDictionarySetValue(status_interface, kSCBondStatusDeviceDistributing, num);		CFRelease(num);		CFDictionarySetValue(status_interfaces, interface, status_interface);		CFRelease(interface);		CFRelease(status_interface);	}	status = __SCBondStatusCreatePrivate(NULL, bond, status_bond, status_interfaces);	CFRelease(status_bond);	CFRelease(status_interfaces);    done:	if (s != -1) {		close(s);	}	if (ibsr_p != NULL) {		free(ibsr_p);	}	return (SCBondStatusRef)status;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:101,


示例21: HIViewAddSubview

void IGraphicsCarbon::CreateTextEntry(IControl* pControl, IText* pText, IRECT* pTextRect, const char* pString, IParam* pParam){  ControlRef control = 0;  if (!pControl || mTextEntryView || !mIsComposited) return;  Rect r = { pTextRect->T, pTextRect->L, pTextRect->B, pTextRect->R };  // these adjustments should make it the same as the cocoa one, i.e. the same size as the pTextRect, but with the extra blue rim often this is too small  //Rect r = { pTextRect->T+4, pTextRect->L+3, pTextRect->B-3, pTextRect->R -3 };  if (CreateEditUnicodeTextControl(NULL, &r, NULL, false, NULL, &control) != noErr) return;  HIViewAddSubview(mView, control);  const EventTypeSpec events[] =  {    { kEventClassKeyboard, kEventRawKeyDown },    { kEventClassKeyboard, kEventRawKeyRepeat }  };  InstallControlEventHandler(control, TextEntryHandler, GetEventTypeCount(events), events, this, &mTextEntryHandler);  mTextEntryView = control;  if (pString[0] != '/0')  {    CFStringRef str = CFStringCreateWithCString(NULL, pString, kCFStringEncodingUTF8);    if (str)    {      SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextCFStringTag, sizeof(str), &str);      CFRelease(str);    }    ControlEditTextSelectionRec sel;    sel.selStart = 0;    sel.selEnd = strlen(pString);    SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextSelectionTag, sizeof(sel), &sel);  }  int just = 0;  switch ( pText->mAlign )  {    case IText::kAlignNear:      just = teJustLeft;      break;    case IText::kAlignCenter:      just = teCenter;      break;    case IText::kAlignFar:      just = teJustRight;      break;    default:      just = teCenter;      break;  }  ControlFontStyleRec font = { kControlUseJustMask | kControlUseSizeMask | kControlUseFontMask, 0, pText->mSize, 0, 0, just, 0, 0 };  CFStringRef str = CFStringCreateWithCString(NULL, pText->mFont, kCFStringEncodingUTF8);  font.font = ATSFontFamilyFindFromName(str, kATSOptionFlagsDefault);  SetControlData(mTextEntryView, kControlEditTextPart, kControlFontStyleTag, sizeof(font), &font);  CFRelease(str);  Boolean singleLineStyle = true;  SetControlData(mTextEntryView, kControlEditTextPart, kControlEditTextSingleLineTag, sizeof (Boolean), &singleLineStyle);  HIViewSetVisible(mTextEntryView, true);  HIViewAdvanceFocus(mTextEntryView, 0);  SetKeyboardFocus(mWindow, mTextEntryView, kControlEditTextPart);  SetUserFocusWindow(mWindow);  mEdControl = pControl;  mEdParam = pParam;}
开发者ID:0x4d52,项目名称:wdl-ol,代码行数:76,


示例22: SCBondInterfaceCopyAvailableMemberInterfaces

CFArrayRef /* of SCNetworkInterfaceRef's */SCBondInterfaceCopyAvailableMemberInterfaces(SCPreferencesRef prefs){	CFMutableArrayRef	available;	CFMutableSetRef		excluded;	CFArrayRef		interfaces;	available = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);	excluded  = CFSetCreateMutable  (NULL, 0, &kCFTypeSetCallBacks);	// exclude Bond [member] interfaces	interfaces = SCBondInterfaceCopyAll(prefs);	if (interfaces != NULL) {		__SCBondInterfaceListCollectMembers(interfaces, excluded);		CFRelease(interfaces);	}	// exclude Bridge [member] interfaces	interfaces = SCBridgeInterfaceCopyAll(prefs);	if (interfaces != NULL) {		__SCBridgeInterfaceListCollectMembers(interfaces, excluded);		CFRelease(interfaces);	}	// exclude VLAN [physical] interfaces	interfaces = SCVLANInterfaceCopyAll(prefs);	if (interfaces != NULL) {		CFIndex	i;		CFIndex	n;		n = CFArrayGetCount(interfaces);		for (i = 0; i < n; i++) {			SCVLANInterfaceRef	vlanInterface;			SCNetworkInterfaceRef	physical;			// exclude the physical interface of this VLAN			vlanInterface = CFArrayGetValueAtIndex(interfaces, i);			physical = SCVLANInterfaceGetPhysicalInterface(vlanInterface);			CFSetAddValue(excluded, physical);		}		CFRelease(interfaces);	}	// identify available interfaces	interfaces = __SCNetworkInterfaceCopyAll_IONetworkInterface();	if (interfaces != NULL) {		CFIndex	i;		CFIndex	n;		n = CFArrayGetCount(interfaces);		for (i = 0; i < n; i++) {			SCNetworkInterfaceRef		interface;			SCNetworkInterfacePrivateRef	interfacePrivate;			interface = CFArrayGetValueAtIndex(interfaces, i);			interfacePrivate = (SCNetworkInterfacePrivateRef)interface;			if (!interfacePrivate->supportsBond) {				// if this interface is not available				continue;			}			if (CFSetContainsValue(excluded, interface)) {				// if excluded				continue;			}			CFArrayAppendValue(available, interface);		}		CFRelease(interfaces);	}	CFRelease(excluded);	return available;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:76,


示例23: UniqueID

MenuRef IGraphicsCarbon::CreateMenu(IPopupMenu* pMenu){  MenuRef menuRef = 0;  ResID menuID = UniqueID ('MENU');  int numItems = pMenu->GetNItems();  if (numItems && CreateNewMenu(menuID, kMenuAttrCondenseSeparators, &menuRef) == noErr)  {    for (int i = 0; i < numItems; ++i)    {      IPopupMenuItem* menuItem = pMenu->GetItem(i);      if (menuItem->GetIsSeparator())      {        AppendMenuItemTextWithCFString(menuRef, CFSTR(""), kMenuItemAttrSeparator, 0, NULL);      }      else      {        CFStringRef itemString = CFStringCreateWithCString(NULL, menuItem->GetText(), kCFStringEncodingUTF8);        if (pMenu->GetPrefix())        {          CFStringRef prefixString = 0;          switch (pMenu->GetPrefix())          {            case 0:              prefixString = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); break;            case 1:              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%1d: "),i+1); break;            case 2:              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%02d: "),i+1); break;            case 3:              prefixString = CFStringCreateWithFormat(NULL, 0, CFSTR("%03d: "),i+1); break;          }          CFMutableStringRef newItemString = CFStringCreateMutable(0, 0);          CFStringAppend (newItemString, prefixString);          CFStringAppend (newItemString, itemString);          CFRelease (itemString);          CFRelease (prefixString);          itemString = newItemString;        }        if (itemString == 0)          continue;        MenuItemAttributes itemAttribs = kMenuItemAttrIgnoreMeta;        if (!menuItem->GetEnabled())        {          itemAttribs |= kMenuItemAttrDisabled;        }        if (menuItem->GetIsTitle())        {          itemAttribs |= kMenuItemAttrSectionHeader;        }        InsertMenuItemTextWithCFString(menuRef, itemString, i, itemAttribs, 0);        if (menuItem->GetChecked())        {          CheckMenuItem(menuRef, i+1, true);        }        if (menuItem->GetSubmenu())        {          MenuRef submenu = CreateMenu(menuItem->GetSubmenu());          if (submenu)          {            SetMenuItemHierarchicalMenu(menuRef, i+1, submenu);            CFRelease (submenu);          }        }        CFRelease (itemString);      }    }    //  if (pMenu->getStyle() & kCheckStyle && !multipleCheck)    //    CheckMenuItem (menuRef, pMenu->getCurrentIndex (true) + 1, true);    SetMenuItemRefCon(menuRef, 0, (int32_t)pMenu);    //swell collision    #undef InsertMenu    InsertMenu(menuRef, kInsertHierarchicalMenu);    #define InsertMenu SWELL_InsertMenu  }  return menuRef;}
开发者ID:0x4d52,项目名称:wdl-ol,代码行数:93,


示例24: SCBondInterfaceCreate

SCBondInterfaceRefSCBondInterfaceCreate(SCPreferencesRef prefs){	CFAllocatorRef		allocator;	SCBondInterfaceRef	bond		= NULL;	CFIndex			i;	if (prefs == NULL) {		_SCErrorSet(kSCStatusInvalidArgument);		return NULL;	}	allocator = CFGetAllocator(prefs);	// create a new bond using an unused interface name	for (i = 0; bond == NULL; i++) {		CFDictionaryRef			dict;		CFStringRef			bond_if;		SCNetworkInterfacePrivateRef	interfacePrivate;		CFMutableDictionaryRef		newDict;		CFArrayRef			newInterfaces;		Boolean				ok;		CFStringRef			path;		bond_if = CFStringCreateWithFormat(allocator, NULL, CFSTR("bond%ld"), i);		path    = CFStringCreateWithFormat(allocator,						   NULL,						   CFSTR("/%@/%@/%@"),						   kSCPrefVirtualNetworkInterfaces,						   kSCNetworkInterfaceTypeBond,						   bond_if);		dict = SCPreferencesPathGetValue(prefs, path);		if (dict != NULL) {			// if bond interface name not available			CFRelease(path);			CFRelease(bond_if);			continue;		}		// add the bond to the stored preferences		newDict = CFDictionaryCreateMutable(allocator,						    0,						    &kCFTypeDictionaryKeyCallBacks,						    &kCFTypeDictionaryValueCallBacks);		newInterfaces = CFArrayCreate(allocator, NULL, 0, &kCFTypeArrayCallBacks);		CFDictionaryAddValue(newDict, kSCPropVirtualNetworkInterfacesBondInterfaces, newInterfaces);		CFRelease(newInterfaces);		ok = SCPreferencesPathSetValue(prefs, path, newDict);		CFRelease(newDict);		CFRelease(path);		if (!ok) {			// if the bond could not be saved			CFRelease(bond_if);			break;		}		// create the SCBondInterfaceRef		bond = (SCBondInterfaceRef)_SCBondInterfaceCreatePrivate(allocator, bond_if);		CFRelease(bond_if);		// estabish link to the stored configuration		interfacePrivate = (SCNetworkInterfacePrivateRef)bond;		interfacePrivate->prefs = CFRetain(prefs);	}	return bond;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:67,


示例25: DaemonTimerCallback

void DaemonTimerCallback( CFRunLoopTimerRef timer, void *info ){/*********Wait if not logging**********/	Boolean validKey;	CFPreferencesAppSynchronize(PREF_DOMAIN);	CFBooleanRef isLogging = (CFPreferencesGetAppBooleanValue(CFSTR("Logging"),PREF_DOMAIN,&validKey))?kCFBooleanTrue:kCFBooleanFalse;	if (!validKey)	{		isLogging = kCFBooleanTrue;		CFPreferencesSetAppValue(CFSTR("Logging"),isLogging,PREF_DOMAIN);	}		if (!CFBooleanGetValue(isLogging))		return;	/********* Check the buffer **********/	int buffsize=0;	int keys=0;	getBufferSizeAndKeys(&buffsize,&keys);	#ifdef LK_DEBUG		syslog(LOG_ERR,"Buffsize %d, Keys %d.",buffsize,keys);		#endif	if (!keys)			// no keyboards logged		return;	if (buffsize < MAX_BUFF_SIZE/10)		return;/********* Get the buffer **********/	CFStringRef the_buffer = getBuffer();	/********* Check defaults/file **********/			CFStringRef curPathName = (CFStringRef)CFPreferencesCopyAppValue(PATHNAME_PREF_KEY,PREF_DOMAIN);	if (!curPathName)		// path has been deleted	{		pathName = CFSTR(DEFAULT_PATHNAME);		CFPreferencesSetAppValue(PATHNAME_PREF_KEY,pathName,PREF_DOMAIN);		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));		if (!logStream)		{			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");				return;		}	}	else if (CFStringCompare(curPathName,pathName,0)!=kCFCompareEqualTo)	// path has changed	{		pathName = curPathName;					logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));		if (!logStream)		{			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");				return;		}				CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,CFDataGetLength(encrypt_buffer)));	}	if (!fileExists(pathName))		// when file is deleted, we resync the encryption & keymap preferences	{		CFPreferencesAppSynchronize(PREF_DOMAIN);		updateEncryption();		updateKeymap();		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false));		if (!logStream)		{			syslog(LOG_ERR,"Error: Couldn't open file stream while running.");				return;		}		stamp_file(CFSTR("LogKext Daemon created new logfile"));	}	if (outOfSpace(pathName))	{		stamp_file(CFSTR("Not enough disk space remaining!"));		return;	}/********* Finally, write the buffer **********/	write_buffer(the_buffer);	CFRelease(the_buffer);				return;}
开发者ID:CiaccoDavide,项目名称:logKext,代码行数:95,


示例26: SCBondInterfaceSetMemberInterfaces

BooleanSCBondInterfaceSetMemberInterfaces(SCBondInterfaceRef bond, CFArrayRef members){	SCNetworkInterfacePrivateRef	interfacePrivate	= (SCNetworkInterfacePrivateRef)bond;	Boolean				ok;	int				sc_status		= kSCStatusOK;	if (!isA_SCBondInterface(bond)) {		_SCErrorSet(kSCStatusInvalidArgument);		return FALSE;	}	if ((members != NULL) && !isA_CFArray(members)) {		_SCErrorSet(kSCStatusInvalidArgument);		return FALSE;	}	if (interfacePrivate->prefs != NULL) {		CFArrayRef	available;		CFArrayRef	current;		CFIndex		i;		CFIndex		n_available;		CFIndex		n_current;		CFIndex		n_members;		CFArrayRef	services	= NULL;		current     = SCBondInterfaceGetMemberInterfaces(bond);		n_current   = (current != NULL) ? CFArrayGetCount(current) : 0;		available   = SCBondInterfaceCopyAvailableMemberInterfaces(interfacePrivate->prefs);		n_available = (available != NULL) ? CFArrayGetCount(available) : 0;		n_members = (members != NULL) ? CFArrayGetCount(members) : 0;		for (i = 0; i < n_members; i++) {			SCNetworkInterfaceRef	member;			member = CFArrayGetValueAtIndex(members, i);			if ((current != NULL) &&			    CFArrayContainsValue(current, CFRangeMake(0, n_current), member)) {				// current members are allowed				continue;			}			if ((available != NULL) &&			    CFArrayContainsValue(available, CFRangeMake(0, n_available), member)) {				// available members are allowed but cannot be associated				// with any other network services.				if (services == NULL) {					services = __SCNetworkServiceCopyAllEnabled(interfacePrivate->prefs);				}				if ((services != NULL) &&				    __SCNetworkServiceExistsForInterface(services, member)) {					sc_status = kSCStatusKeyExists;					break;				}				// if available				continue;			}			// if member not allowed			sc_status = kSCStatusInvalidArgument;			break;		}		if (available != NULL) CFRelease(available);		if (services != NULL) CFRelease(services);	}	if (sc_status != kSCStatusOK) {		_SCErrorSet(sc_status);		return FALSE;	}	ok = _SCBondInterfaceSetMemberInterfaces(bond, members);	return ok;}
开发者ID:alfintatorkace,项目名称:osx-10.9-opensource,代码行数:79,


示例27: main

int main(){	if (geteuid())	{		syslog(LOG_ERR,"Error: Daemon must run as root.");		exit(geteuid());	}	encrypt_buffer = CFDataCreateMutable(kCFAllocatorDefault,8);	/*********Set up File**********/	if (!(pathName = (CFStringRef)CFPreferencesCopyAppValue(PATHNAME_PREF_KEY,PREF_DOMAIN)))	{		pathName = CFSTR(DEFAULT_PATHNAME);		CFPreferencesSetAppValue(PATHNAME_PREF_KEY,pathName,PREF_DOMAIN);	}	CFURLRef logPathURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false);		logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,logPathURL);	CFRelease(logPathURL);	if (!logStream)	{		syslog(LOG_ERR,"Error: Couldn't open file stream at start.");			return 1;	}/*********Check encryption & keymap**********/	updateEncryption();	updateKeymap();/*********Check space**********/	if (outOfSpace(pathName))	{		stamp_file(CFSTR("Not enough disk space remaining!"));		CFRunLoopStop(CFRunLoopGetCurrent());	}/*********Connect to kernel extension**********/		if (!connectToKext())	{		if (load_kext())		{			stamp_file(CFSTR("Could not load KEXT"));			return 1;		}		if (!connectToKext())		{			stamp_file(CFSTR("Could not connect with KEXT"));			return 1;		}	}	sleep(1);		// just a little time to let the kernel notification handlers finish		stamp_file(CFSTR("LogKext Daemon starting up"));	// stamp login file with initial user	LoginLogoutCallBackFunction(NULL, NULL, NULL);		CFPreferencesAppSynchronize(PREF_DOMAIN);	/*********Create Daemon Timer source**********/	CFRunLoopTimerContext timerContext = { 0 };	CFRunLoopSourceRef loginLogoutSource;	    if (InstallLoginLogoutNotifiers(&loginLogoutSource))		syslog(LOG_ERR,"Error: could not install login notifier");	else		CFRunLoopAddSource(CFRunLoopGetCurrent(),loginLogoutSource, kCFRunLoopDefaultMode);	CFRunLoopTimerRef daemonTimer = CFRunLoopTimerCreate(NULL, 0, TIME_TO_SLEEP, 0, 0, DaemonTimerCallback, &timerContext);	CFRunLoopAddTimer(CFRunLoopGetCurrent(), daemonTimer, kCFRunLoopCommonModes);		CFRunLoopRun();		stamp_file(CFSTR("Server error: closing Daemon"));		CFWriteStreamClose(logStream);}
开发者ID:CiaccoDavide,项目名称:logKext,代码行数:82,


示例28: IOServiceMatching

RString ArchHooks_MacOSX::GetMachineId() const{	RString ret;	CFMutableDictionaryRef dict = IOServiceMatching( "IOPlatformExpertDevice" );	CFMutableDictionaryRef property;	io_service_t service;	if( dict )	{		// This consumes the reference.		service = IOServiceGetMatchingService( kIOMasterPortDefault, dict );		if( service )		{			CFTypeRef serial;			CFStringRef key = CFSTR( "IOPlatformSerialNumber" ); // kIOPlatformSerialNumberKey			serial = IORegistryEntryCreateCFProperty( service, key, kCFAllocatorDefault, 0 );			if( serial )			{				const char *str = CFStringGetCStringPtr( (CFStringRef)serial, CFStringGetSystemEncoding() );				ret = str? str:"";				CFRelease( serial );			}			IOObjectRelease( service );		}	}	dict = IOServiceMatching( kIOEthernetInterfaceClass );	if( !dict )		return ret;	property = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,					      &kCFTypeDictionaryValueCallBacks );	if( !property )	{		CFRelease( dict );		return ret;	}	CFDictionarySetValue( property, CFSTR(kIOPrimaryInterface), kCFBooleanTrue );	CFDictionarySetValue( dict, CFSTR(kIOPropertyMatchKey), property );	CFRelease( property );	io_iterator_t iter;	if( IOServiceGetMatchingServices(kIOMasterPortDefault, dict, &iter) != KERN_SUCCESS )		return ret;	while( (service = IOIteratorNext(iter)) )	{		CFTypeRef data;		io_object_t controller;		if( IORegistryEntryGetParentEntry(service, kIOServicePlane, &controller) != KERN_SUCCESS )		{			IOObjectRelease( service );			continue;		}		data = IORegistryEntryCreateCFProperty( controller, CFSTR(kIOMACAddress),							kCFAllocatorDefault, 0 );		if( data )		{			const uint8_t *p = CFDataGetBytePtr( (CFDataRef)data );						ret += ssprintf( "-%02x:%02x:%02x:%02x:%02x:%02x",					 p[0], p[1], p[2], p[3], p[4], p[5] );			CFRelease( data );		}		IOObjectRelease( controller );		IOObjectRelease( service );	}	IOObjectRelease( iter );	return ret;}
开发者ID:Ancaro,项目名称:stepmania,代码行数:78,


示例29: qDebug

//.........这里部分代码省略.........                    usbids.insert(id, name);                    qDebug() << "[System] USB:" << QString("0x%1").arg(id, 8, 16) << name;                }                u = u->next;            }        }        b = b->next;    }#endif#endif#if defined(Q_OS_MACX)    kern_return_t result = KERN_FAILURE;    CFMutableDictionaryRef usb_matching_dictionary;    io_iterator_t usb_iterator = IO_OBJECT_NULL;    usb_matching_dictionary = IOServiceMatching(kIOUSBDeviceClassName);    result = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_matching_dictionary,                                          &usb_iterator);    if(result) {        qDebug() << "[System] USB: IOKit: Could not get matching services.";        return usbids;    }    io_object_t usbCurrentObj;    while((usbCurrentObj = IOIteratorNext(usb_iterator))) {        uint32_t id;        QString name;        /* get vendor ID */        CFTypeRef vidref = NULL;        int vid = 0;        vidref = IORegistryEntryCreateCFProperty(usbCurrentObj, CFSTR("idVendor"),                                kCFAllocatorDefault, 0);        CFNumberGetValue((CFNumberRef)vidref, kCFNumberIntType, &vid);        CFRelease(vidref);        /* get product ID */        CFTypeRef pidref = NULL;        int pid = 0;        pidref = IORegistryEntryCreateCFProperty(usbCurrentObj, CFSTR("idProduct"),                                kCFAllocatorDefault, 0);        CFNumberGetValue((CFNumberRef)pidref, kCFNumberIntType, &pid);        CFRelease(pidref);        id = vid << 16 | pid;        /* get product vendor */        char vendor_buf[256];        CFIndex vendor_buflen = 256;        CFTypeRef vendor_name_ref = NULL;        vendor_name_ref = IORegistryEntrySearchCFProperty(usbCurrentObj,                                 kIOServicePlane, CFSTR("USB Vendor Name"),                                 kCFAllocatorDefault, 0);        if(vendor_name_ref != NULL) {            CFStringGetCString((CFStringRef)vendor_name_ref, vendor_buf, vendor_buflen,                               kCFStringEncodingUTF8);            name += QString::fromUtf8(vendor_buf) + " ";            CFRelease(vendor_name_ref);        }        else {            name += QObject::tr("(unknown vendor name) ");        }        /* get product name */        char product_buf[256];        CFIndex product_buflen = 256;        CFTypeRef product_name_ref = NULL;
开发者ID:4nykey,项目名称:rockbox,代码行数:67,



注:本文中的CFRelease函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ CFReleaseNull函数代码示例
C++ CFReadStreamOpen函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。