Python和C交互-回调函数

joo*_*oon 5 c python

我正在为我的一个研究项目制作Mac OS的按键记录器。我有一个C代码,它将捕获击键并将其写入文本文件。(以下代码我取出了一些不重要的东西)

我现在需要做的就像PyHook一样,而不是将数据写入文本文件,而是将Python回调函数传递给C代码,并使它将键输入传递回Python,因此我可以使用Python进行必要的分析。

我一直在寻找方法,但老实说,我不知道该如何处理,因为我不习惯C编程或Python扩展。任何帮助将不胜感激。

#include <Carbon/Carbon.h>
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>

#define NUM_RECORDING_EVENT_TYPES 5
#define RECORD 0
#define MOUSEACTION 0
#define KEYSTROKE 1
// maximum expected line length, for fgets
#define LINE_LENGTH 80
#define kShowMouse TRUE

OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData);

void prepareToRecord(); // install the event handler, wait for record signal

// note that keyboard character codes are found in Figure C2 of the document
// Inside Macintosh: Text available from http://developer.apple.com
char * keyStringForKeyCode(int keyCode); // get the representation of the Mac keycode

// Global Variables
int dieNow = 0;    // should the program terminate
int ifexit = 0;       // Exit state 
char *filename = NULL;  // Log file name
FILE *fd = NULL;   // Log file descriptor

int typecount = 0;          // count keystroke to periodically save to a txt file

struct timeval thetime;  // for gettimeofday
long currenttime;   // the current time in milliseconds

int main()
{
    filename = "test.txt";
    fd = fopen(filename, "a");

    // Get RUI ready to record or play, based off of mode
    prepareToRecord();

 return EXIT_SUCCESS;
}

// event handler for RUI recorder
OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData)
{
 // Determine class and kind of event
    int eventClass = GetEventClass(theEvent);
    int eventKind = GetEventKind(theEvent);

    /* Handle Keyboard Events */
    if((eventClass == kEventClassKeyboard) && (eventKind == kEventRawKeyDown)) /* key release implied */ {
        int keyCode, modifiers;  // what did the user press? any modifier keys down?

  // gather keystroke information
        GetEventParameter(theEvent, kEventParamKeyCode, typeInteger, NULL, sizeof(keyCode), NULL, &keyCode);
        GetEventParameter(theEvent, kEventParamKeyModifiers, typeInteger, NULL, sizeof(modifiers), NULL, &modifiers);

        // What time is it?
        gettimeofday(&thetime, NULL);
        currenttime =(((thetime.tv_sec*1000000) + (thetime.tv_usec)));

  fprintf(fd, "%s\n", keyStringForKeyCode(keyCode));

    } 

    return EXIT_SUCCESS;
}


void prepareToRecord()
{
 EventRecord event;  // holds an event for examination

    // Types of events to listen for
    EventTypeSpec eventTypes[NUM_RECORDING_EVENT_TYPES] = {{kEventClassKeyboard, kEventRawKeyDown}};

 // Install the event handler
    InstallEventHandler(GetEventMonitorTarget(), NewEventHandlerUPP(RUIRecordingEventOccurred), NUM_RECORDING_EVENT_TYPES, eventTypes, nil, nil);

    // event loop - get events until die command
 do {
        WaitNextEvent((everyEvent),&event,GetCaretTime(),nil);
 } while (dieNow == 0);
}


char * keyStringForKeyCode(int keyCode)
{
 // return key char
 switch (keyCode) {
  case 0: return("a");
 default: return("Empty"); // Unknown key, Return "Empty"
 }
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*aju 4

这很简单 - 只需按照说明进行操作即可 -从 C 调用 Python 函数(2022 年 3 月更新:对于 Python3,请参阅扩展和嵌入 Python 解释器中的相应章节)。

或者,如果您尝试从 Python 调用 C/C++ 函数,您可以使用SWIG或 Python 的模块CType之一