https://blog.csdn.net/wenming111/article/details/103717431
http://www.swig.org/Doc3.0/CSharp.html#CSharp_directors_implementation
git分支:master
git地址:https://gitee.com/yichichunshui/swigcsharp.git
git节点:19c948ed30147b93272c9cb213cf486064509247
使用过程:
定义一个简单的类person.h
#pragma once
class person
{
public:
person(void);
person(int birthYear);
int GetBirthYear();
~person(void);
private:
int m_BirthYear;
};
实现:person.cpp
#include "person.h"
person::person(void)
{
m_BirthYear=0;
}
person::person(int birthYear)
{
m_BirthYear=birthYear;
}
int person::GetBirthYear()
{
return m_BirthYear;
}
person::~person(void)
{
}
swigcharp的生成后事件:
swig -c++ -csharp -o swig_wrap.cpp -namespace "swigcharp_person" -outdir "E:\OGL3\DLL\swigcsharp\c++swigcsharp\swigcsharp" -dllimport swigcsharpdll swigconfig.i
生成得到文件:
我们把:swig_wrap.cpp添加到c++项目:swigcsharp
再次重新生成,得到:
把他拷贝到:
重新命名为:swigcsharpdll.dll
然后将:把peson.cs和swigcsharpdllPINVOKE.cs拷贝到SwigApp中去,在C#项目中如下测试:
class Program
{
static void Main(string[] args)
{
person ps = new person(18);
Console.WriteLine("我今年"+ ps.GetBirthYear()+"岁");
}
}
测试调用成功。
下面介绍一个多态类的写法。这个参考:https://www.swig.org/Doc3.0/CSharp.html#CSharp_multiple_modules
20.6 C# Directors这个节
在C++定义一个基类:
#pragma once
#include <iostream>
class Base {
public:
virtual ~Base() {}
virtual unsigned int UIntMethod(unsigned int x) {
std::cout << "Base - UIntMethod(" << x << ")" << std::endl;
return x;
}
virtual void BaseBoolMethod(const Base& b, bool flag) {}
};
class Caller {
public:
Caller() : m_base(0) {}
~Caller() { delBase(); }
void set(Base* b) { delBase(); m_base = b; }
void reset() { m_base = 0; }
unsigned int UIntMethodCall(unsigned int x) { return m_base->UIntMethod(x); }
private:
Base* m_base;
void delBase() { delete m_base; m_base = 0; }
};
导出文件配置:swigconfig.i内容:
directors=“1”,为1表示打开多态,然后feature属性标记Base为多态类:
%module(directors="1") swigcsharpdll
%{
#include "person.h"
#include "example.h"
%}
%feature("director") Base;
%include "person.h"
%include "example.h"
四个文件拷贝到:SwigApp项目中,同时还要把dll拷贝到SwigApp中去
我们在C#中,写了一个继承Base的子类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace swigcharp_person
{
public class CSharpDerived : Base
{
public override uint UIntMethod(uint x)
{
Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
return x;
}
}
}
C#中测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using swigcharp_person;
namespace SwigApp
{
class Program
{
static void Main(string[] args)
{
person ps = new person(18);
Console.WriteLine("我今年"+ ps.GetBirthYear()+"岁");
Caller myCaller = new Caller();
// Test pure C++ class
using (Base myBase = new Base())
{
makeCalls(myCaller, myBase);
}
// Test director / C# derived class
using (Base myBase = new CSharpDerived())
{
makeCalls(myCaller, myBase);
}
Console.ReadKey();
}
static void makeCalls(Caller myCaller, Base myBase)
{
myCaller.set(myBase);
myCaller.UIntMethodCall(123);
myCaller.reset();
}
}
}
最后测试成功实现了多态: