首先,我想說我沒有修改甚至查看c源代碼的選項,因此涉及修改c文件的任何內容都不會有幫助。使用cython將一個回調函數從python傳遞到c
在VP.h:
typedef enum VPEvent {
...
EVENT_OBJECT_CLICK,
...
}
...
typedef void *VPInstance;
typedef void(*VPEventHandler)(VPInstance);
...
VPSDK_API VPInstance vp_create(void);
...
VPSDK_API int vp_event_set(VPInstance instance, VPEvent eventname, VPEventHandler event);
...
在VP.pyx:
cdef extern from "VP.h":
...
cdef enum VPEvent:
...
VP_EVENT_OBJECT_CLICK,
...
...
ctypedef void *VPInstance
ctypedef void(*VPEventHandler)(VPInstance)
...
VPInstance vp_create()
...
int vp_event_set(VPInstance instance, VPEvent eventname, VPEventHandler event)
...
...
EVENT_OBJECT_CLICK = VP_EVENT_OBJECT_CLICK
...
cdef class create:
cdef VPInstance instance
def __init__(self):
self.instance = vp_create()
...
def event_set(self, eventname, event):
return vp_event_set(self.instance, eventname, event)
我想有在Python什麼:
import VP
...
def click(bot):
bot.say("Someone clicked something!")
...
bot = VP.create()
bot.event_set(VP.EVENT_OBJECT_CLICK, click)
這是你會怎麼做在c:
#include <VP.h>
void click(VPInstance instance) {
vp_say(instance, "Someone clicked something!");
}
int main(int argc, char ** argv) {
...
VPInstance instance;
instance = vp_create();
...
vp_event_set(instance, VP_EVENT_OBJECT_CLICK, click)
}
然而問題是,編譯VP.pyx當我得到
不能Python對象轉換爲「VPEventHandler」
同時,默認情況下,回調賦予了VPInstance指針,但我想將這個值抽象成一個類。
謝謝版本!這是我見過的使用python對象使用指針處理的唯一Cython示例。即投到。 –
Rebs