찾다
백엔드 개발C++RGFW 심층 분석: 클립보드 복사/붙여넣기

RGFW Under the Hood: Clipboard Copy/Paste

Introduction

Reading and writing to the clipboard using low-level APIs can be tricky. There are a bunch of steps required. This tutorial simplifies the process so you can easily read and write to the clipboard using the low-level APIs.

The tutorial is based on RGFW's source code and its usage of the low-level APIs.

Note: the cocoa code is written in Pure-C.

Overview

1) Clipboard Paste

  • X11 (init atoms, convert section, get data)
  • Win32 (open clipboard, get data, convert data, close clipboard)
  • Cocoa (set datatypes, get pasteboard, get data, convert data)

2) Clipboard Copy

  • X11 (init atoms, convert section, handle request, send data)
  • Win32 (setup global object, convert data, open clipboard, convert string, send data, close clipboard)
  • Cocoa (create datatype array, declare types, convert string, send data)

Clipboard Paste

X11

To handle the clipboard, you must create some Atoms via XInternAtom.
X Atoms are used to ask for or send specific data or properties through X11.

You'll need three atoms,

1) UTF8_STRING: Atom for a UTF-8 string.
2) CLIPBOARD: Atom for getting clipboard data.
3) XSEL_DATA: Atom to get selection data.

const Atom UTF8_STRING = XInternAtom(display, "UTF8_STRING", True);
const Atom CLIPBOARD = XInternAtom(display, "CLIPBOARD", 0);
const Atom XSEL_DATA = XInternAtom(display, "XSEL_DATA", 0);

Now, to get the clipboard data you have to request that the clipboard section be converted to UTF8 using XConvertSelection.

use XSync to send the request to the server.

XConvertSelection(display, CLIPBOARD, UTF8_STRING, XSEL_DATA, window, CurrentTime);
XSync(display, 0);

The selection will be converted and sent back to the client as a XSelectionNotify event. You can get the next event, which should be the SelectionNotify event with XNextEvent.

XEvent event;
XNextEvent(display, &event);

Check if the event is a SelectionNotify event and use .selection to ensure the type is a CLIPBOARD. Also make sure .property is not 0 and can be retrieved.

if (event.type == SelectionNotify && event.xselection.selection == CLIPBOARD && event.xselection.property != 0) {

You can get the converted data via XGetWindowProperty using the selection property.

    int format;
    unsigned long N, size;
    char* data, * s = NULL;
    Atom target;

    XGetWindowProperty(event.xselection.display, event.xselection.requestor,
        event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target,
        &format, &size, &N, (unsigned char**) &data);

Make sure the data is in the right format by checking target

    if (target == UTF8_STRING || target == XA_STRING) {

The data is stored in data, once you're done with it free it with XFree.

You can also delete the property via XDeleteProperty.

        XFree(data);
    }

    XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
}

winapi

First, open the clipboard OpenClipboard.

if (OpenClipboard(NULL) == 0)
    return 0;

Get the clipboard data as a utf16 string via GetClipboardData

If the data is NULL, you should close the clipboard using CloseClipboard

HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == NULL) {
    CloseClipboard();
    return 0;
}

Next, you need to convert the utf16 data back to utf8.

Start by locking memory for the utf8 data via GlobalLock.

wchar_t* wstr = (wchar_t*) GlobalLock(hData);

Use setlocale to ensure the data format is utf8.

Get the size of the UTF-8 version with wcstombs.

setlocale(LC_ALL, "en_US.UTF-8");

size_t textLen = wcstombs(NULL, wstr, 0);

If the size is valid, convert the data using wcstombs.

if (textLen) {
    char* text = (char*) malloc((textLen * sizeof(char)) + 1);

    wcstombs(text, wstr, (textLen) + 1);
    text[textLen] = '\0';

    free(text);
}

Make sure to free leftover global data using GlobalUnlock and close the clipboard with CloseClipboard.

GlobalUnlock(hData);
CloseClipboard();

cocoa

Cocoa uses NSPasteboardTypeString to ask for string data. You'll have to define this yourself if you're not using Objective-C.

NSPasteboardType const NSPasteboardTypeString = "public.utf8-plain-text";

Although the is a c-string and Cocoa uses NSStrings, you can convert the c-string to an NSString via stringWithUTF8String.

NSString* dataType = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), (char*)NSPasteboardTypeString);

Now we'll use generalPasteboard to get the default pasteboard object.

NSPasteboard* pasteboard = objc_msgSend_id((id)objc_getClass("NSPasteboard"), sel_registerName("generalPasteboard")); 

Then you can get the pasteboard's string data with the dataType using stringForType.

However, it will give you an NSString, which can be converted with UTF8String.

NSString* clip = ((id(*)(id, SEL, const char*))objc_msgSend)(pasteboard, sel_registerName("stringForType:"), dataType);
const char* str = ((const char* (*)(id, SEL)) objc_msgSend) (clip, sel_registerName("UTF8String"));

Clipboard Copy

X11

To copy to the clipboard you'll need a few more Atoms.

1) SAVE_TARGETS: To request a section to convert to (for copying).
2) TARGETS: To handle one requested target
3) MULTIPLE: When there are multiple request targets
4) ATOM_PAIR: To get the supported data types.
5) CLIPBOARD_MANAGER: To access data from the clipboard manager.

const Atom SAVE_TARGETS = XInternAtom((Display*) display, "SAVE_TARGETS", False);
const Atom TARGETS = XInternAtom((Display*) display, "TARGETS", False);
const Atom MULTIPLE = XInternAtom((Display*) display, "MULTIPLE", False);
const Atom ATOM_PAIR = XInternAtom((Display*) display, "ATOM_PAIR", False);
const Atom CLIPBOARD_MANAGER = XInternAtom((Display*) display, "CLIPBOARD_MANAGER", False);

We can request a clipboard section. First, set the owner of the section to be a client window via XSetSelectionOwner. Next request a converted section using XConvertSelection.

XSetSelectionOwner((Display*) display, CLIPBOARD, (Window) window, CurrentTime);

XConvertSelection((Display*) display, CLIPBOARD_MANAGER, SAVE_TARGETS, None, (Window) window, CurrentTime);

The rest of the code would exist in an event loop. You can create an external event loop from your main event loop if you wish or add this to your main event loop.

We'll be handling SelectionRequest in order to update the clipboard selection to the string data.

if (event.type == SelectionRequest) {
    const XSelectionRequestEvent* request = &event.xselectionrequest;

At the end of the SelectionNotify event, a response will be sent back to the requester. The structure should be created here and modified depending on the request data.

    XEvent reply = { SelectionNotify };
    reply.xselection.property = 0;

The first target we will handle is TARGETS when the requestor wants to know which targets are supported.

    if (request->target == TARGETS) {

I will create an array of supported targets

        const Atom targets[] = { TARGETS,
                                MULTIPLE,
                                UTF8_STRING,
                                XA_STRING };

This array can be passed using XChangeProperty.

I'll also change the selection property so the requestor knows what property we changed.

        XChangeProperty(display,
            request->requestor,
            request->property,
            4,
            32,
            PropModeReplace,
            (unsigned char*) targets,
            sizeof(targets) / sizeof(targets[0]));

        reply.xselection.property = request->property;
    }

Next, I will handle MULTIPLE targets.

    if (request->target == MULTIPLE) {

We'll start by getting the supported targets via XGetWindowProperty

        Atom* targets = NULL;

        Atom actualType = 0;
        int actualFormat = 0;
        unsigned long count = 0, bytesAfter = 0;

        XGetWindowProperty(display, request->requestor, request->property, 0, LONG_MAX, False, ATOM_PAIR, &actualType, &actualFormat, &count, &bytesAfter, (unsigned char **) &targets);

Now we'll loop through the supported targets. If the supported targets match one of our supported targets, we can pass the data with XChangeProperty.

If the target is not used, the second argument should be set to None, marking it as unused.

        unsigned long i;
        for (i = 0; i requestor,
                    targets[i + 1],
                    targets[i],
                    8,
                    PropModeReplace,
                    (unsigned char*) text,
                    sizeof(text));
                XFlush(display);
            } else {
                targets[i + 1] = None;
            }
        }

You can pass the final array of supported targets to the requestor using XChangeProperty. This tells the requestor which targets to expect for the original list it sent.

The message will be sent out asap when XFlush is called.

You can free your copy of the target array with XFree.

        XChangeProperty((Display*) display,
            request->requestor,
            request->property,
            ATOM_PAIR,
            32,
            PropModeReplace,
            (unsigned char*) targets,
            count);

        XFlush(display);
        XFree(targets);

        reply.xselection.property = request->property;
    }

For the final step of the event, send the selection back to the requestor via XSendEvent.

Then flush the queue with XFlush.

    reply.xselection.display = request->display;
    reply.xselection.requestor = request->requestor;
    reply.xselection.selection = request->selection;
    reply.xselection.target = request->target;
    reply.xselection.time = request->time;

    XSendEvent((Display*) display, request->requestor, False, 0, &reply);
    XFlush(display);
}

winapi

First allocate global memory for your data and your utf-8 buffer with GlobalAlloc

HANDLE object = GlobalAlloc(GMEM_MOVEABLE, (1 + textLen) * sizeof(WCHAR));
WCHAR*  buffer = (WCHAR*) GlobalLock(object);

Next, you can use MultiByteToWideChar to convert your string to a wide string.

MultiByteToWideChar(CP_UTF8, 0, text, -1, buffer, textLen);

Now unlock the global object and open the clipboard

GlobalUnlock(object);
OpenClipboard(NULL);

To update the clipboard data, you start by clearing what's currently on the clipboard via EmptyClipboard you can use SetClipboardData to set the data to the utf8 object.

Finally, close the clipboard with CloseClipboard.

EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, object);

CloseClipboard();

cocoa

Start by creating an array of the type of data you want to put on the clipboard and convert it to an NSArray using initWithObjects.

NSPasteboardType ntypes[] = { dataType };

NSArray* array = ((id (*)(id, SEL, void*, NSUInteger))objc_msgSend)
                    (NSAlloc(objc_getClass("NSArray")), sel_registerName("initWithObjects:count:"), ntypes, 1);

Use declareTypes to declare the array as the supported data types.

You can also free the NSArray with NSRelease.

((NSInteger(*)(id, SEL, id, void*))objc_msgSend) (pasteboard, sel_registerName("declareTypes:owner:"), array, NULL);
NSRelease(array);

You can convert the string to want to copy to an NSString via stringWithUTF8String and set the clipboard string to be that NSString using setString.

NSString* nsstr = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), text);

((bool (*)(id, SEL, id, NSPasteboardType))objc_msgSend) (pasteboard, sel_registerName("setString:forType:"), nsstr, dataType);  

Full examples

X11

// compile with:
// gcc x11.c -lX11

#include 
#include 
#include 
#include 
#include 

#include 

int main(void) {
    Display* display = XOpenDisplay(NULL);

    Window window = XCreateSimpleWindow(display, RootWindow(display, DefaultScreen(display)), 10, 10, 200, 200, 1,
                                 BlackPixel(display, DefaultScreen(display)), WhitePixel(display, DefaultScreen(display)));

    XSelectInput(display, window, ExposureMask | KeyPressMask); 

    const Atom UTF8_STRING = XInternAtom(display, "UTF8_STRING", True);
    const Atom CLIPBOARD = XInternAtom(display, "CLIPBOARD", 0);
    const Atom XSEL_DATA = XInternAtom(display, "XSEL_DATA", 0);

    const Atom SAVE_TARGETS = XInternAtom((Display*) display, "SAVE_TARGETS", False);
    const Atom TARGETS = XInternAtom((Display*) display, "TARGETS", False);
    const Atom MULTIPLE = XInternAtom((Display*) display, "MULTIPLE", False);
    const Atom ATOM_PAIR = XInternAtom((Display*) display, "ATOM_PAIR", False);
    const Atom CLIPBOARD_MANAGER = XInternAtom((Display*) display, "CLIPBOARD_MANAGER", False);

    // input
    XConvertSelection(display, CLIPBOARD, UTF8_STRING, XSEL_DATA, window, CurrentTime);
    XSync(display, 0);

    XEvent event;
    XNextEvent(display, &event);

    if (event.type == SelectionNotify && event.xselection.selection == CLIPBOARD && event.xselection.property != 0) {

        int format;
        unsigned long N, size;
        char* data, * s = NULL;
        Atom target;

        XGetWindowProperty(event.xselection.display, event.xselection.requestor,
            event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target,
            &format, &size, &N, (unsigned char**) &data);

        if (target == UTF8_STRING || target == XA_STRING) {
            printf("paste: %s\n", data);
            XFree(data);
        }

        XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
    }

    // output
    char text[] = "new string\0";

    XSetSelectionOwner((Display*) display, CLIPBOARD, (Window) window, CurrentTime);

    XConvertSelection((Display*) display, CLIPBOARD_MANAGER, SAVE_TARGETS, None, (Window) window, CurrentTime);

    Bool running = True;
    while (running) {
        XNextEvent(display, &event);
        if (event.type == SelectionRequest) {
            const XSelectionRequestEvent* request = &event.xselectionrequest;

            XEvent reply = { SelectionNotify };
            reply.xselection.property = 0;

            if (request->target == TARGETS) {
                const Atom targets[] = { TARGETS,
                                        MULTIPLE,
                                        UTF8_STRING,
                                        XA_STRING };

                XChangeProperty(display,
                    request->requestor,
                    request->property,
                    4,
                    32,
                    PropModeReplace,
                    (unsigned char*) targets,
                    sizeof(targets) / sizeof(targets[0]));

                reply.xselection.property = request->property;
            }

            if (request->target == MULTIPLE) {  
                Atom* targets = NULL;

                Atom actualType = 0;
                int actualFormat = 0;
                unsigned long count = 0, bytesAfter = 0;

                XGetWindowProperty(display, request->requestor, request->property, 0, LONG_MAX, False, ATOM_PAIR, &actualType, &actualFormat, &count, &bytesAfter, (unsigned char **) &targets);

                unsigned long i;
                for (i = 0; i requestor,
                            targets[i + 1],
                            targets[i],
                            8,
                            PropModeReplace,
                            (unsigned char*) text,
                            sizeof(text));
                        XFlush(display);
                        running = False;
                    } else {
                        targets[i + 1] = None;
                    }
                }

                XChangeProperty((Display*) display,
                    request->requestor,
                    request->property,
                    ATOM_PAIR,
                    32,
                    PropModeReplace,
                    (unsigned char*) targets,
                    count);

                XFlush(display);
                XFree(targets);

                reply.xselection.property = request->property;
            }

            reply.xselection.display = request->display;
            reply.xselection.requestor = request->requestor;
            reply.xselection.selection = request->selection;
            reply.xselection.target = request->target;
            reply.xselection.time = request->time;

            XSendEvent((Display*) display, request->requestor, False, 0, &reply);
            XFlush(display);
        }
    }

    XCloseDisplay(display);
 }

Winapi

// compile with:
// gcc win32.c

#include <windows.h>
#include <locale.h>

#include <stdio.h>

int main() {
    // output
    if (OpenClipboard(NULL) == 0)
        return 0;

    HANDLE hData = GetClipboardData(CF_UNICODETEXT);
    if (hData == NULL) {
        CloseClipboard();
        return 0;
    }

    wchar_t* wstr = (wchar_t*) GlobalLock(hData);

    setlocale(LC_ALL, "en_US.UTF-8");

    size_t textLen = wcstombs(NULL, wstr, 0);

    if (textLen) {
        char* text = (char*) malloc((textLen * sizeof(char)) + 1);

        wcstombs(text, wstr, (textLen) + 1);
        text[textLen] = '\0';

        printf("paste: %s\n", text);
        free(text);
    }

    GlobalUnlock(hData);
    CloseClipboard();


    // input

    char text[] = "new text\0";

    HANDLE object = GlobalAlloc(GMEM_MOVEABLE, (sizeof(text) / sizeof(char))  * sizeof(WCHAR));

    WCHAR* buffer = (WCHAR*) GlobalLock(object);
    if (!buffer) {
        GlobalFree(object);
        return 0;
    }

    MultiByteToWideChar(CP_UTF8, 0, text, -1, buffer, (sizeof(text) / sizeof(char)));

    GlobalUnlock(object);
    if (OpenClipboard(NULL) == 0) {
        GlobalFree(object);
        return 0;
    }

    EmptyClipboard();
    SetClipboardData(CF_UNICODETEXT, object);
    CloseClipboard();
}
</stdio.h></locale.h></windows.h>

Cocoa

// compile with:
// gcc cocoa.c -framework Foundation -framework AppKit  


#include 
#include 
#include 
#include 

#ifdef __arm64__
/* ARM just uses objc_msgSend */
#define abi_objc_msgSend_stret objc_msgSend
#define abi_objc_msgSend_fpret objc_msgSend
#else /* __i386__ */
/* x86 just uses abi_objc_msgSend_fpret and (NSColor *)objc_msgSend_id respectively */
#define abi_objc_msgSend_stret objc_msgSend_stret
#define abi_objc_msgSend_fpret objc_msgSend_fpret
#endif

typedef void NSPasteboard;
typedef void NSString;
typedef void NSArray;
typedef void NSApplication;

typedef const char* NSPasteboardType;

typedef unsigned long NSUInteger;
typedef long NSInteger;

#define NSAlloc(nsclass) objc_msgSend_id((id)nsclass, sel_registerName("alloc"))

#define objc_msgSend_bool           ((BOOL (*)(id, SEL))objc_msgSend)
#define objc_msgSend_void           ((void (*)(id, SEL))objc_msgSend)
#define objc_msgSend_void_id        ((void (*)(id, SEL, id))objc_msgSend)
#define objc_msgSend_uint           ((NSUInteger (*)(id, SEL))objc_msgSend)
#define objc_msgSend_void_bool      ((void (*)(id, SEL, BOOL))objc_msgSend)
#define objc_msgSend_void_int       ((void (*)(id, SEL, int))objc_msgSend)
#define objc_msgSend_bool_void      ((BOOL (*)(id, SEL))objc_msgSend)
#define objc_msgSend_void_SEL       ((void (*)(id, SEL, SEL))objc_msgSend)
#define objc_msgSend_id             ((id (*)(id, SEL))objc_msgSend)
#define objc_msgSend_id_id              ((id (*)(id, SEL, id))objc_msgSend)
#define objc_msgSend_id_bool            ((BOOL (*)(id, SEL, id))objc_msgSend)

#define objc_msgSend_class_char ((id (*)(Class, SEL, char*))objc_msgSend)

void NSRelease(id obj) {
    objc_msgSend_void(obj, sel_registerName("release"));
}

int main() {
    /* input */
    NSPasteboardType const NSPasteboardTypeString = "public.utf8-plain-text";

    NSString* dataType = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), (char*)NSPasteboardTypeString);

    NSPasteboard* pasteboard = objc_msgSend_id((id)objc_getClass("NSPasteboard"), sel_registerName("generalPasteboard")); 

    NSString* clip = ((id(*)(id, SEL, const char*))objc_msgSend)(pasteboard, sel_registerName("stringForType:"), dataType);

    const char* str = ((const char* (*)(id, SEL)) objc_msgSend) (clip, sel_registerName("UTF8String"));

    printf("paste: %s\n", str);

    char text[] = "new string\0";

    NSPasteboardType ntypes[] = { dataType };

    NSArray* array = ((id (*)(id, SEL, void*, NSUInteger))objc_msgSend)
                        (NSAlloc(objc_getClass("NSArray")), sel_registerName("initWithObjects:count:"), ntypes, 1);

    ((NSInteger(*)(id, SEL, id, void*))objc_msgSend) (pasteboard, sel_registerName("declareTypes:owner:"), array, NULL);
    NSRelease(array);

    NSString* nsstr = objc_msgSend_class_char(objc_getClass("NSString"), sel_registerName("stringWithUTF8String:"), text);

    ((bool (*)(id, SEL, id, NSPasteboardType))objc_msgSend) (pasteboard, sel_registerName("setString:forType:"), nsstr, dataType);  
}

위 내용은 RGFW 심층 분석: 클립보드 복사/붙여넣기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
C 커뮤니티 : 자원, 지원 및 개발C 커뮤니티 : 자원, 지원 및 개발Apr 13, 2025 am 12:01 AM

C 학습자와 개발자는 StackoverFlow, Reddit의 R/CPP 커뮤니티, Coursera 및 EDX 코스, GitHub의 오픈 소스 프로젝트, 전문 컨설팅 서비스 및 CPPCon에서 리소스와 지원을받을 수 있습니다. 1. StackoverFlow는 기술적 인 질문에 대한 답변을 제공합니다. 2. Reddit의 R/CPP 커뮤니티는 최신 뉴스를 공유합니다. 3. Coursera와 Edx는 공식적인 C 과정을 제공합니다. 4. LLVM 및 부스트 기술 향상과 같은 GitHub의 오픈 소스 프로젝트; 5. JetBrains 및 Perforce와 같은 전문 컨설팅 서비스는 기술 지원을 제공합니다. 6. CPPCON 및 기타 회의는 경력을 돕습니다

C# vs. C : 각 언어가 탁월한 곳C# vs. C : 각 언어가 탁월한 곳Apr 12, 2025 am 12:08 AM

C#은 높은 개발 효율성과 크로스 플랫폼 지원이 필요한 프로젝트에 적합한 반면 C#은 고성능 및 기본 제어가 필요한 응용 프로그램에 적합합니다. 1) C#은 개발을 단순화하고, 쓰레기 수집 및 리치 클래스 라이브러리를 제공하며, 엔터프라이즈 레벨 애플리케이션에 적합합니다. 2) C는 게임 개발 및 고성능 컴퓨팅에 적합한 직접 메모리 작동을 허용합니다.

C의 지속적인 사용 : 지구력의 이유C의 지속적인 사용 : 지구력의 이유Apr 11, 2025 am 12:02 AM

C 지속적인 사용 이유에는 고성능, 광범위한 응용 및 진화 특성이 포함됩니다. 1) 고효율 성능 : C는 메모리 및 하드웨어를 직접 조작하여 시스템 프로그래밍 및 고성능 컴퓨팅에서 훌륭하게 수행합니다. 2) 널리 사용 : 게임 개발, 임베디드 시스템 등의 분야에서의 빛나기.

C 및 XML의 미래 : 신흥 동향 및 기술C 및 XML의 미래 : 신흥 동향 및 기술Apr 10, 2025 am 09:28 AM

C 및 XML의 미래 개발 동향은 다음과 같습니다. 1) C는 프로그래밍 효율성 및 보안을 개선하기 위해 C 20 및 C 23 표준을 통해 모듈, 개념 및 코 루틴과 같은 새로운 기능을 소개합니다. 2) XML은 데이터 교환 및 구성 파일에서 중요한 위치를 계속 차지하지만 JSON 및 YAML의 문제에 직면하게 될 것이며 XMLSCHEMA1.1 및 XPATH 3.1의 개선과 같이보다 간결하고 쉽게 구문 분석하는 방향으로 발전 할 것입니다.

현대 C 디자인 패턴 : 확장 가능하고 유지 관리 가능한 소프트웨어 구축현대 C 디자인 패턴 : 확장 가능하고 유지 관리 가능한 소프트웨어 구축Apr 09, 2025 am 12:06 AM

최신 C 설계 모델은 C 11 이상의 새로운 기능을 사용하여보다 유연하고 효율적인 소프트웨어를 구축 할 수 있습니다. 1) Lambda Expressions 및 STD :: 함수를 사용하여 관찰자 패턴을 단순화하십시오. 2) 모바일 의미와 완벽한 전달을 통해 성능을 최적화하십시오. 3) 지능형 포인터는 유형 안전 및 자원 관리를 보장합니다.

C 다중 스레딩 및 동시성 : 병렬 프로그래밍 마스터 링C 다중 스레딩 및 동시성 : 병렬 프로그래밍 마스터 링Apr 08, 2025 am 12:10 AM

C 멀티 스레딩 및 동시 프로그래밍의 핵심 개념에는 스레드 생성 및 관리, 동기화 및 상호 제외, 조건부 변수, 스레드 풀링, 비동기 프로그래밍, 일반적인 오류 및 디버깅 기술, 성능 최적화 및 모범 사례가 포함됩니다. 1) std :: 스레드 클래스를 사용하여 스레드를 만듭니다. 예제는 스레드가 완성 될 때까지 생성하고 기다리는 방법을 보여줍니다. 2) std :: mutex 및 std :: lock_guard를 사용하여 공유 리소스를 보호하고 데이터 경쟁을 피하기 위해 동기화 및 상호 배제. 3) 조건 변수는 std :: 조건 _variable을 통한 스레드 간의 통신과 동기화를 실현합니다. 4) 스레드 풀 예제는 ThreadPool 클래스를 사용하여 효율성을 향상시키기 위해 작업을 병렬로 처리하는 방법을 보여줍니다. 5) 비동기 프로그래밍은 std :: as를 사용합니다

C Deep Dive : 메모리 관리, 포인터 및 템플릿 마스터 링C Deep Dive : 메모리 관리, 포인터 및 템플릿 마스터 링Apr 07, 2025 am 12:11 AM

C의 메모리 관리, 포인터 및 템플릿은 핵심 기능입니다. 1. 메모리 관리는 새롭고 삭제를 통해 메모리를 수동으로 할당하고 릴리스하며 힙과 스택의 차이에주의를 기울입니다. 2. 포인터는 메모리 주소를 직접 작동시키고주의해서 사용할 수 있습니다. 스마트 포인터는 관리를 단순화 할 수 있습니다. 3. 템플릿은 일반적인 프로그래밍을 구현하고 코드 재사용 성과 유연성을 향상 시키며 유형 파생 및 전문화를 이해해야합니다.

C 및 시스템 프로그래밍 : 저수준 제어 및 하드웨어 상호 작용C 및 시스템 프로그래밍 : 저수준 제어 및 하드웨어 상호 작용Apr 06, 2025 am 12:06 AM

C는 시스템 프로그래밍 및 하드웨어 상호 작용에 적합합니다. 하드웨어에 가까운 제어 기능 및 객체 지향 프로그래밍의 강력한 기능을 제공하기 때문입니다. 1) C는 포인터, 메모리 관리 및 비트 운영과 같은 저수준 기능을 통해 효율적인 시스템 수준 작동을 달성 할 수 있습니다. 2) 하드웨어 상호 작용은 장치 드라이버를 통해 구현되며 C는 이러한 드라이버를 작성하여 하드웨어 장치와의 통신을 처리 할 수 ​​있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.