将C ++回调转换为Java [英] Convert a C++ callback to Java
问题描述
我在C ++(Cocos2d)中有以下代码:
I have the following code in C++ (Cocos2d) :
typedef void (CCObject::*SEL_CallFunc)();
CCCallFunc * CCCallFunc::actionWithTarget(CCObject* pSelectorTarget,
SEL_CallFunc selector) {
CCCallFunc *pRet = new CCCallFunc();
if (pRet && pRet->initWithTarget(pSelectorTarget)) {
pRet->m_pCallFunc = selector;
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
使用swig转换为java时,我得到以下内容:
When converting with swig to java I get the following :
public static CCCallFunc actionWithTarget(CCObject pSelectorTarget, SWIGTYPE_m_CCObject__f___void selector) {
long cPtr = cocos2dxMappingJNI.CCCallFunc_actionWithTarget(CCObject.getCPtr(pSelectorTarget), pSelectorTarget,
SWIGTYPE_m_CCObject__f___void.getCMemberPtr(selector));
return (cPtr == 0) ? null : new CCCallFunc(cPtr, false);
}
其中 SWIGTYPE_m_CCObject__f ___ void
是只是一个我不能使用的指针。
Where SWIGTYPE_m_CCObject__f___void
is just a pointer I can't use.
如何在SWIG界面中实现这一点?
我已经研究过这个解决方案 stackoverflow 但无法为我的情况实现它。
How do I implement this in the SWIG interface ? I've looked into this solution stackoverflow but couldn't implement it for my case.
推荐答案
我不相信SWIG以任何有意义的方式支持成员函数指针。但是,可以使用 JavaCPP 完成此操作。鉴于此文件中的C ++代码名为 MemberFunction.h
:
I don't believe SWIG supports member function pointers in any meaningful way. However, it's possible to get it done with JavaCPP. Given this C++ code in a file named MemberFunction.h
:
class MyClass {
public:
virtual ~MyClass() { }
};
typedef void (MyClass::*MyFunction)(const char *str);
void callback(MyClass* cls, MyFunction fct, const char *str) {
(cls->*fct)(str);
}
我们可以在Java中以这种方式定义和使用回调:
We can define and use the callback this way in Java:
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
@Platform(include="MemberFunction.h")
public class MemberFunction {
static { Loader.load(); }
public static abstract class MyClass extends Pointer {
public MyClass() { allocate(); }
private native void allocate();
@Virtual public abstract void myCallback(String str);
@Virtual @MemberGetter @Name("myCallback")
public static native MyFunction getMyCallback();
}
@Namespace("MyClass")
public static class MyFunction extends FunctionPointer {
public native void call(MyClass cls, String str);
}
public static native void callback(MyClass cls, MyFunction fct, String str);
public static void main(String[] args) {
MyClass cls = new MyClass() {
public void myCallback(String str) {
System.out.println(str);
}
};
MyFunction fct = MyClass.getMyCallback();
callback(cls, fct, "Hello World");
}
}
哪种构建正常并输出预期结果:
Which builds fine and outputs the expected result:
$ javac -cp javacpp.jar MemberFunction.java
$ java -jar javacpp.jar MemberFunction
$ java -cp javacpp.jar MemberFunction
Hello World
这篇关于将C ++回调转换为Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!