SWIG - C++同C#的混合编程(二)
2014-12-02 19:27
447 查看
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"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;}
相关文章推荐
- SWIG入门 - c++ 同 c# 的混合编程
- C#与DLL和COM的混合编程(1)-C#调用C++写的非托管的DLL中导出的函数
- 谈谈Matlab与C/C++或C#的互调用(混合编程)
- 通过Swig使C#可以链接C++编译的dll[勘误和修改]
- 【语言桥接】(windows)swig-C#封装 C++教程
- C#与C++混合编程
- SWIG,把C/C++ API 导出成Java,C#,Python,Ruby,Php的类库
- C#和C++混合编程
- C#和C++混合编程
- swig--在java、C#中调用c++写的DLL(以vs2012配置为例)
- C#与C++混合编程---C++/CX语法
- [转贴] C#与C++的混合编程
- Swig转c++ lib项目到c#可引用的dll
- C#和C++混合编程
- Swig将C++编译lib项目转换为C#可引用的dll[勘误后]
- Swig转c++ lib项目到c#可引用的dll
- C#和C++混合编程
- C#和C++混合编程(ZZ)
- c# 与c++ 混合编程
- C#和C++混合编程