标签:blog http io ar os sp on 文件 2014
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* * 功能:演示C++对C#的回调 * 最后更新日期:2014-04-19 * 作者: Kagula * 测试环境:Windows8.1 64bits, Visual Studio 2013 Update1, SWIG Win 3.0.0 * */ namespace SWIG_Tutorial3_CSharp { class Program { static void Main(string[] args) { //测试C++对C#代码的回调 Caller myCaller = new Caller(); // Test pure C++ class using (Base myBase = new Base()) { makeCalls(myCaller, myBase);//C++控制台输出 } // Test director / C# derived class using (Base myBase = new CSharpDerived()) { makeCalls(myCaller, myBase);//C#控制台输出 } //按任意键,退出应用程序 Console.ReadKey(); } /* 设置回调对象,并回调 */ static void makeCalls(Caller myCaller, Base myBase) { myCaller.set(myBase); myCaller.UIntMethodCall(123); } } /* 测试对C++继承类的回调 */ public class CSharpDerived : Base { public override uint UIntMethod(uint x) { Console.WriteLine("CSharpDerived - UIntMethod({0})", x); return x; } } }
SWIG_Tutorial3.i文件清单
<pre name="code" class="plain">%module(directors="1") SWIG_Tutorial3 /* directors的设置是为了使SWIG支持回调 */ %{ /* 指定在当前文本中要引用到的头文件 */ #include "Caller.h" %} %feature("director") Base; /* 设置Base, C++回调C#用的基类 */ /* 解析头文件 */ %include "Caller.h"
<pre name="code" class="cpp">#pragma once /* 功能:演示C++对C#的回调机制 作者:Kagula 测试环境:Windows 8.1 64bits, Visual Studio 203 Update1, SWIG Win3.0.0 参考资料:http://www.swig.org/Doc3.0/CSharp.html#CSharp_directors_example */ class Base { public: virtual unsigned int UIntMethod(unsigned int x); }; class Caller { public: Caller() : m_base(nullptr) {} /* 不要释放从C#传进来的指针,这里遵循谁分配谁释放原则 */ void set(Base *b) { m_base = b; } /* 回调测试 */ unsigned int UIntMethodCall(unsigned int x) { if (m_base == nullptr) return -1; return m_base->UIntMethod(x);//callback } private: Base *m_base; };
Caller.cpp
#include "Caller.h" #include <iostream> unsigned int Base::UIntMethod(unsigned int x) { std::cout << "Base - UIntMethod(" << x << ")" << std::endl; return x; }
标签:blog http io ar os sp on 文件 2014
原文地址:http://blog.csdn.net/lee353086/article/details/41682431