SWIG和PInvoke学习(1)

时间:2023-03-09 17:08:10
SWIG和PInvoke学习(1)

1. 简介  

  SWIG是个帮助使用C或者C++编写的软件能与其它各种高级编程语言进行嵌入联接的开发工具。

  SWIG能应用于各种不同类型的语言包括常用脚本编译语言例如Perl, PHP, Python, Tcl, Ruby and PHP。支持语言列表中也包括非脚本编译语言,例如C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), Java, Modula-3, OCAML以及R,甚至是编译器或者汇编的计划应用(Guile, MzScheme, Chicken)。SWIG普遍应用于创建高级语言解析或汇编程序环境,用户接口,作为一种用来测试C/C++或进行原型设计的工具。SWIG还能够导出XML或Lisp s-expressions格式的解析树。

  SWIG可以被*使用,发布,修改用于商业或非商业中。

2.使用方法学习

  从官网下载了swigwin-2.0.11。

  Swig使用大概有两种方式,一种是配置Vs对外部工具,一种是配置环境变量通过Cmd命令。前一种方法比较简单,Vs2010配置如图。

  SWIG和PInvoke学习(1)

测试使用的步骤和相关的类。

1.新建VC Win32空项目Dll

2. 添加类CMath

 #pragma once
class CMath
{
public:
CMath(void);
~CMath(void);
int Add(int a, int b);
int n;
};

实现文件:

SWIG和PInvoke学习(1)
 #include "Math.h"

 CMath::CMath(void)
{
} CMath::~CMath(void)
{
} int CMath::Add(int a, int b)
{
return a+b;
}

Math.cpp

3.添加一个test.i文件,添加代码,注意module名要和编译C++的dll名称一致。

当前页执行外部工具Swig,生成4个文件:Test_wrap.cxx,CMath.cs,MathLib.cs和MathLibPINVOKE.cs。

 %module MathLib
%include <windows.i> %{
#include "Math.h"
%} %include "Math.h"
SWIG和PInvoke学习(1)
 /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */ #define SWIGCSHARP #ifdef __cplusplus
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
struct SwigMovePointer {
T *ptr;
SwigMovePointer(T *p) : ptr(p) { }
~SwigMovePointer() { delete ptr; }
SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = ; delete oldptr; ptr = rhs.ptr; rhs.ptr = ; return *this; }
} pointer;
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
SwigValueWrapper() : pointer() { }
SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
operator T&() const { return *pointer.ptr; }
T *operator&() { return pointer.ptr; }
}; template <typename T> T SwigValueInit() {
return T();
}
#endif /* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif /* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif /* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > || (__GNUC__ == && __GNUC_MINOR__ >= ))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif #ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : ) /* unreferenced local function has been removed */
# endif
#endif #ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif /* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif /* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif /* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif #ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif /* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif #include <stdlib.h>
#include <string.h>
#include <stdio.h> /* Support for throwing C# exceptions from C/C++. There are two types:
* Exceptions that take a message and ArgumentExceptions that take a message and a parameter name. */
typedef enum {
SWIG_CSharpApplicationException,
SWIG_CSharpArithmeticException,
SWIG_CSharpDivideByZeroException,
SWIG_CSharpIndexOutOfRangeException,
SWIG_CSharpInvalidCastException,
SWIG_CSharpInvalidOperationException,
SWIG_CSharpIOException,
SWIG_CSharpNullReferenceException,
SWIG_CSharpOutOfMemoryException,
SWIG_CSharpOverflowException,
SWIG_CSharpSystemException
} SWIG_CSharpExceptionCodes; typedef enum {
SWIG_CSharpArgumentException,
SWIG_CSharpArgumentNullException,
SWIG_CSharpArgumentOutOfRangeException
} SWIG_CSharpExceptionArgumentCodes; typedef void (SWIGSTDCALL* SWIG_CSharpExceptionCallback_t)(const char *);
typedef void (SWIGSTDCALL* SWIG_CSharpExceptionArgumentCallback_t)(const char *, const char *); typedef struct {
SWIG_CSharpExceptionCodes code;
SWIG_CSharpExceptionCallback_t callback;
} SWIG_CSharpException_t; typedef struct {
SWIG_CSharpExceptionArgumentCodes code;
SWIG_CSharpExceptionArgumentCallback_t callback;
} SWIG_CSharpExceptionArgument_t; static SWIG_CSharpException_t SWIG_csharp_exceptions[] = {
{ SWIG_CSharpApplicationException, NULL },
{ SWIG_CSharpArithmeticException, NULL },
{ SWIG_CSharpDivideByZeroException, NULL },
{ SWIG_CSharpIndexOutOfRangeException, NULL },
{ SWIG_CSharpInvalidCastException, NULL },
{ SWIG_CSharpInvalidOperationException, NULL },
{ SWIG_CSharpIOException, NULL },
{ SWIG_CSharpNullReferenceException, NULL },
{ SWIG_CSharpOutOfMemoryException, NULL },
{ SWIG_CSharpOverflowException, NULL },
{ SWIG_CSharpSystemException, NULL }
}; static SWIG_CSharpExceptionArgument_t SWIG_csharp_exceptions_argument[] = {
{ SWIG_CSharpArgumentException, NULL },
{ SWIG_CSharpArgumentNullException, NULL },
{ SWIG_CSharpArgumentOutOfRangeException, NULL }
}; static void SWIGUNUSED SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code, const char *msg) {
SWIG_CSharpExceptionCallback_t callback = SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback;
if ((size_t)code < sizeof(SWIG_csharp_exceptions)/sizeof(SWIG_CSharpException_t)) {
callback = SWIG_csharp_exceptions[code].callback;
}
callback(msg);
} static void SWIGUNUSED SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code, const char *msg, const char *param_name) {
SWIG_CSharpExceptionArgumentCallback_t callback = SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback;
if ((size_t)code < sizeof(SWIG_csharp_exceptions_argument)/sizeof(SWIG_CSharpExceptionArgument_t)) {
callback = SWIG_csharp_exceptions_argument[code].callback;
}
callback(msg, param_name);
} #ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionCallbacks_MathLib(
SWIG_CSharpExceptionCallback_t applicationCallback,
SWIG_CSharpExceptionCallback_t arithmeticCallback,
SWIG_CSharpExceptionCallback_t divideByZeroCallback,
SWIG_CSharpExceptionCallback_t indexOutOfRangeCallback,
SWIG_CSharpExceptionCallback_t invalidCastCallback,
SWIG_CSharpExceptionCallback_t invalidOperationCallback,
SWIG_CSharpExceptionCallback_t ioCallback,
SWIG_CSharpExceptionCallback_t nullReferenceCallback,
SWIG_CSharpExceptionCallback_t outOfMemoryCallback,
SWIG_CSharpExceptionCallback_t overflowCallback,
SWIG_CSharpExceptionCallback_t systemCallback) {
SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback = applicationCallback;
SWIG_csharp_exceptions[SWIG_CSharpArithmeticException].callback = arithmeticCallback;
SWIG_csharp_exceptions[SWIG_CSharpDivideByZeroException].callback = divideByZeroCallback;
SWIG_csharp_exceptions[SWIG_CSharpIndexOutOfRangeException].callback = indexOutOfRangeCallback;
SWIG_csharp_exceptions[SWIG_CSharpInvalidCastException].callback = invalidCastCallback;
SWIG_csharp_exceptions[SWIG_CSharpInvalidOperationException].callback = invalidOperationCallback;
SWIG_csharp_exceptions[SWIG_CSharpIOException].callback = ioCallback;
SWIG_csharp_exceptions[SWIG_CSharpNullReferenceException].callback = nullReferenceCallback;
SWIG_csharp_exceptions[SWIG_CSharpOutOfMemoryException].callback = outOfMemoryCallback;
SWIG_csharp_exceptions[SWIG_CSharpOverflowException].callback = overflowCallback;
SWIG_csharp_exceptions[SWIG_CSharpSystemException].callback = systemCallback;
} #ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_MathLib(
SWIG_CSharpExceptionArgumentCallback_t argumentCallback,
SWIG_CSharpExceptionArgumentCallback_t argumentNullCallback,
SWIG_CSharpExceptionArgumentCallback_t argumentOutOfRangeCallback) {
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback = argumentCallback;
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentNullException].callback = argumentNullCallback;
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentOutOfRangeException].callback = argumentOutOfRangeCallback;
} /* Callback for returning strings to C# without leaking memory */
typedef char * (SWIGSTDCALL* SWIG_CSharpStringHelperCallback)(const char *);
static SWIG_CSharpStringHelperCallback SWIG_csharp_string_callback = NULL; #ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterStringCallback_MathLib(SWIG_CSharpStringHelperCallback callback) {
SWIG_csharp_string_callback = callback;
} /* Contract support */ #define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, msg, ""); return nullreturn; } else #include "Math.h" #ifdef __cplusplus
extern "C" {
#endif SWIGEXPORT void * SWIGSTDCALL CSharp_new_CMath() {
void * jresult ;
CMath *result = ; result = (CMath *)new CMath();
jresult = (void *)result;
return jresult;
} SWIGEXPORT void SWIGSTDCALL CSharp_delete_CMath(void * jarg1) {
CMath *arg1 = (CMath *) ; arg1 = (CMath *)jarg1;
delete arg1;
} SWIGEXPORT int SWIGSTDCALL CSharp_CMath_Add(void * jarg1, int jarg2, int jarg3) {
int jresult ;
CMath *arg1 = (CMath *) ;
int arg2 ;
int arg3 ;
int result; arg1 = (CMath *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
result = (int)(arg1)->Add(arg2,arg3);
jresult = result;
return jresult;
} SWIGEXPORT void SWIGSTDCALL CSharp_CMath_n_set(void * jarg1, int jarg2) {
CMath *arg1 = (CMath *) ;
int arg2 ; arg1 = (CMath *)jarg1;
arg2 = (int)jarg2;
if (arg1) (arg1)->n = arg2;
} SWIGEXPORT int SWIGSTDCALL CSharp_CMath_n_get(void * jarg1) {
int jresult ;
CMath *arg1 = (CMath *) ;
int result; arg1 = (CMath *)jarg1;
result = (int) ((arg1)->n);
jresult = result;
return jresult;
} #ifdef __cplusplus
}
#endif

Test_wrap.cxx

SWIG和PInvoke学习(1)
 /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */ using System;
using System.Runtime.InteropServices; public class CMath : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn; internal CMath(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
} internal static HandleRef getCPtr(CMath obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
} ~CMath() {
Dispose();
} public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
MathLibPINVOKE.delete_CMath(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
} public CMath() : this(MathLibPINVOKE.new_CMath(), true) {
} public int Add(int a, int b) {
int ret = MathLibPINVOKE.CMath_Add(swigCPtr, a, b);
return ret;
} public int n {
set {
MathLibPINVOKE.CMath_n_set(swigCPtr, value);
}
get {
int ret = MathLibPINVOKE.CMath_n_get(swigCPtr);
return ret;
}
} }

CMath.cs

SWIG和PInvoke学习(1)
 /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */ using System;
using System.Runtime.InteropServices; public class MathLib {
}

MathLib.cs

SWIG和PInvoke学习(1)
 /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */ using System;
using System.Runtime.InteropServices; class MathLibPINVOKE { protected class SWIGExceptionHelper { public delegate void ExceptionDelegate(string message);
public delegate void ExceptionArgumentDelegate(string message, string paramName); static ExceptionDelegate applicationDelegate = new ExceptionDelegate(SetPendingApplicationException);
static ExceptionDelegate arithmeticDelegate = new ExceptionDelegate(SetPendingArithmeticException);
static ExceptionDelegate divideByZeroDelegate = new ExceptionDelegate(SetPendingDivideByZeroException);
static ExceptionDelegate indexOutOfRangeDelegate = new ExceptionDelegate(SetPendingIndexOutOfRangeException);
static ExceptionDelegate invalidCastDelegate = new ExceptionDelegate(SetPendingInvalidCastException);
static ExceptionDelegate invalidOperationDelegate = new ExceptionDelegate(SetPendingInvalidOperationException);
static ExceptionDelegate ioDelegate = new ExceptionDelegate(SetPendingIOException);
static ExceptionDelegate nullReferenceDelegate = new ExceptionDelegate(SetPendingNullReferenceException);
static ExceptionDelegate outOfMemoryDelegate = new ExceptionDelegate(SetPendingOutOfMemoryException);
static ExceptionDelegate overflowDelegate = new ExceptionDelegate(SetPendingOverflowException);
static ExceptionDelegate systemDelegate = new ExceptionDelegate(SetPendingSystemException); static ExceptionArgumentDelegate argumentDelegate = new ExceptionArgumentDelegate(SetPendingArgumentException);
static ExceptionArgumentDelegate argumentNullDelegate = new ExceptionArgumentDelegate(SetPendingArgumentNullException);
static ExceptionArgumentDelegate argumentOutOfRangeDelegate = new ExceptionArgumentDelegate(SetPendingArgumentOutOfRangeException); [DllImport("MathLib", EntryPoint="SWIGRegisterExceptionCallbacks_MathLib")]
public static extern void SWIGRegisterExceptionCallbacks_MathLib(
ExceptionDelegate applicationDelegate,
ExceptionDelegate arithmeticDelegate,
ExceptionDelegate divideByZeroDelegate,
ExceptionDelegate indexOutOfRangeDelegate,
ExceptionDelegate invalidCastDelegate,
ExceptionDelegate invalidOperationDelegate,
ExceptionDelegate ioDelegate,
ExceptionDelegate nullReferenceDelegate,
ExceptionDelegate outOfMemoryDelegate,
ExceptionDelegate overflowDelegate,
ExceptionDelegate systemExceptionDelegate); [DllImport("MathLib", EntryPoint="SWIGRegisterExceptionArgumentCallbacks_MathLib")]
public static extern void SWIGRegisterExceptionCallbacksArgument_MathLib(
ExceptionArgumentDelegate argumentDelegate,
ExceptionArgumentDelegate argumentNullDelegate,
ExceptionArgumentDelegate argumentOutOfRangeDelegate); static void SetPendingApplicationException(string message) {
SWIGPendingException.Set(new System.ApplicationException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingArithmeticException(string message) {
SWIGPendingException.Set(new System.ArithmeticException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingDivideByZeroException(string message) {
SWIGPendingException.Set(new System.DivideByZeroException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingIndexOutOfRangeException(string message) {
SWIGPendingException.Set(new System.IndexOutOfRangeException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingInvalidCastException(string message) {
SWIGPendingException.Set(new System.InvalidCastException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingInvalidOperationException(string message) {
SWIGPendingException.Set(new System.InvalidOperationException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingIOException(string message) {
SWIGPendingException.Set(new System.IO.IOException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingNullReferenceException(string message) {
SWIGPendingException.Set(new System.NullReferenceException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingOutOfMemoryException(string message) {
SWIGPendingException.Set(new System.OutOfMemoryException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingOverflowException(string message) {
SWIGPendingException.Set(new System.OverflowException(message, SWIGPendingException.Retrieve()));
}
static void SetPendingSystemException(string message) {
SWIGPendingException.Set(new System.SystemException(message, SWIGPendingException.Retrieve()));
} static void SetPendingArgumentException(string message, string paramName) {
SWIGPendingException.Set(new System.ArgumentException(message, paramName, SWIGPendingException.Retrieve()));
}
static void SetPendingArgumentNullException(string message, string paramName) {
Exception e = SWIGPendingException.Retrieve();
if (e != null) message = message + " Inner Exception: " + e.Message;
SWIGPendingException.Set(new System.ArgumentNullException(paramName, message));
}
static void SetPendingArgumentOutOfRangeException(string message, string paramName) {
Exception e = SWIGPendingException.Retrieve();
if (e != null) message = message + " Inner Exception: " + e.Message;
SWIGPendingException.Set(new System.ArgumentOutOfRangeException(paramName, message));
} static SWIGExceptionHelper() {
SWIGRegisterExceptionCallbacks_MathLib(
applicationDelegate,
arithmeticDelegate,
divideByZeroDelegate,
indexOutOfRangeDelegate,
invalidCastDelegate,
invalidOperationDelegate,
ioDelegate,
nullReferenceDelegate,
outOfMemoryDelegate,
overflowDelegate,
systemDelegate); SWIGRegisterExceptionCallbacksArgument_MathLib(
argumentDelegate,
argumentNullDelegate,
argumentOutOfRangeDelegate);
}
} protected static SWIGExceptionHelper swigExceptionHelper = new SWIGExceptionHelper(); public class SWIGPendingException {
[ThreadStatic]
private static Exception pendingException = null;
private static int numExceptionsPending = ; public static bool Pending {
get {
bool pending = false;
if (numExceptionsPending > )
if (pendingException != null)
pending = true;
return pending;
}
} public static void Set(Exception e) {
if (pendingException != null)
throw new ApplicationException("FATAL: An earlier pending exception from unmanaged code was missed and thus not thrown (" + pendingException.ToString() + ")", e);
pendingException = e;
lock(typeof(MathLibPINVOKE)) {
numExceptionsPending++;
}
} public static Exception Retrieve() {
Exception e = null;
if (numExceptionsPending > ) {
if (pendingException != null) {
e = pendingException;
pendingException = null;
lock(typeof(MathLibPINVOKE)) {
numExceptionsPending--;
}
}
}
return e;
}
} protected class SWIGStringHelper { public delegate string SWIGStringDelegate(string message);
static SWIGStringDelegate stringDelegate = new SWIGStringDelegate(CreateString); [DllImport("MathLib", EntryPoint="SWIGRegisterStringCallback_MathLib")]
public static extern void SWIGRegisterStringCallback_MathLib(SWIGStringDelegate stringDelegate); static string CreateString(string cString) {
return cString;
} static SWIGStringHelper() {
SWIGRegisterStringCallback_MathLib(stringDelegate);
}
} static protected SWIGStringHelper swigStringHelper = new SWIGStringHelper(); static MathLibPINVOKE() {
} [DllImport("MathLib", EntryPoint="CSharp_new_CMath")]
public static extern IntPtr new_CMath(); [DllImport("MathLib", EntryPoint="CSharp_delete_CMath")]
public static extern void delete_CMath(HandleRef jarg1); [DllImport("MathLib", EntryPoint="CSharp_CMath_Add")]
public static extern int CMath_Add(HandleRef jarg1, int jarg2, int jarg3); [DllImport("MathLib", EntryPoint="CSharp_CMath_n_set")]
public static extern void CMath_n_set(HandleRef jarg1, int jarg2); [DllImport("MathLib", EntryPoint="CSharp_CMath_n_get")]
public static extern int CMath_n_get(HandleRef jarg1);
}

MathLibPINVOKE.cs

4.在Vc项目中添加Test_wrap.cxx,编译。生成dll :MathLib.dll。拷贝到新建的C#项目运行目录下。
5.在C#项目中添加CMath.cs,MathLib.cs和MathLibPINVOKE.cs,可以直接编译C#的Dll,也可以直接调用CMath的CLR类。

C#调用代码:

SWIG和PInvoke学习(1)
   private void button1_Click(object sender, EventArgs e)
{
CMath math = new CMath();
int c=math.Add(, );
MessageBox.Show(c.ToString()); }