创建一个调用其他Lua函数的C ++函数

时间:2018-07-03 01:15:41

标签: c++ function lua swig

我想知道是否有可能创建一个以Lua函数为参数来调用它的C ++函数。

例如在Lua中,

function sub()
  print('I am sub function')
end

function main()
  callfunc(sub) //C++ function that takes a function variable to call 
end

是否可以在C ++中创建callfunc()函数?

我正在使用SWIG。

1 个答案:

答案 0 :(得分:2)

您可以使用特殊的lua_fnptr.i标头将Lua解释器状态传递给C ++函数来创建回调。头文件还包含更多使用信息。

enter code here
import spacy
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span

class EntityMatcher(object):
    name = 'entity_matcher'

    def __init__(self, nlp, terms, label):
        patterns = [nlp(text) for text in terms]
        self.matcher = PhraseMatcher(nlp.vocab)
        self.matcher.add(label, None, *patterns)

    def __call__(self, doc):
        matches = self.matcher(doc)
        for match_id, start, end in matches:
            span = Span(doc, start, end, label=match_id)
            doc.ents = list(doc.ents) + [span]
        return doc

nlp = spacy.load('en_core_web_sm')
terms = (u'cat', u'dog', u'tree kangaroo', u'giant sea spider')
entity_matcher = EntityMatcher(nlp, terms, 'ANIMAL')

nlp.add_pipe(entity_matcher, after='ner')
print(nlp.pipe_names)  # the components in the pipeline

doc = nlp(u"This is a text about Barack Obama and a tree kangaroo")
print([(ent.text, ent.label_) for ent in doc.ents])

****[Error]****
File "new.py", line 17, in __call__
span = Span(doc, start, end, label=match_id)
File "span.pyx", line 62, in spacy.tokens.span.Span.__cinit__
ValueError: [E084] Error assigning label ID 893087899 to span: not in 
StringStore.
%module callback

%include <lua_fnptr.i>

%{
void callfunc(SWIGLUA_FN fn) {
    SWIGLUA_FN_GET(fn);
    lua_call(fn.L,0,0);
}
%}

void callfunc(SWIGLUA_FN fn);
local cb = require("callback")
function hello()
    print("Hello World!")
end
cb.callfunc(hello)