Python和C交互 - 回调函数

时间:2010-09-30 04:38:47

标签: python c

我正在尝试为我的一个研究项目制作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"
 }
}

1 个答案:

答案 0 :(得分:4)

这很简单 - 只需按照说明操作 - Calling Python Functions from C

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